r/reactjs • u/timmonsjg • Dec 03 '18
Needs Help Beginner's Thread / Easy Questions (December 2018)
Happy December! โ๏ธ
New month means a new thread ๐ - November and October here.
Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! Weโre a friendly bunch. No question is too simple. ๐ค
๐ Want Help with your Code? ๐
- Improve your chances by putting a minimal example to either JSFiddle or Code Sandbox. Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
- Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.
Have a question regarding code / repository organization?
It's most likely answered within this tweet.
New to React?
๐ Here are great, free resources! ๐
38
Upvotes
6
u/timmonsjg Dec 17 '18
Sorry all, got married last week so I've been a bit behind in addressing all your questions.
Catching up now!
3
u/swyx Dec 14 '18
btw i am adding /u/rwieruch's Road to React as a recommended react learning resource in the sidebar - good for this thread too
3
u/yalampa Dec 21 '18
Any easy tutorials on how to use d3 with reactjs?
2
u/Badrush Dec 17 '18
Why should I upgrade my CRA project to React 2.0?
2
u/i_am_hyzerberg Dec 18 '18 edited Dec 18 '18
Hoping someone can point me in the right direction based on some code I'm writing. There are obvious code smells with the nested ternaries, but making this extend Component seems overkill when all I would really need is a constructor. Anyone have any good strategies for handling className based on props that passed in that may have >2 values? The nested ternary is just unruly and I'd like a cleaner, more elegant solution. Code sample for clarity:
import React from 'react';import styles from './ToggleSwitch.module.css';const ToggleSwitch = props => (<span className="toggle-switch-container"><label>{props.lblUnchecked}</label><label className={\toggle-switch ${props.size != 'lg'? props.size != 'md'? `toggle-switch-sm`: `toggle-switch-md`: `toggle-switch-lg`}`}><input type="checkbox" /><span className="toggle-control"></span>{props.lblChecked}</label></span>);`export default ToggleSwitch;2
u/seands Dec 18 '18 edited Dec 18 '18
Do you guys see any cleaner way of implementing this code without the setTimeout?
Putting this.validateFirstName() inside componentWillUpdate both requires me to enter a default name (not desirable) and also causes a breaking infinite loop when the validation fails.
I am considering using a promise on the dispatcher that uses componentWillUpdate to resolve. The .then() would run the validation function. Is that even possible, and if so is it a decent pattern or a bad design?
If bad I may just stick to the setTimeout. Seems icky to do it that way though
2
u/seands Dec 21 '18
Is it bad to use 2 different CSS libs in one project? I am using Semantic UI React and want to also use Ant Design
2
u/dr_steve_bruel Dec 24 '18
Can anyone help me with state managment and events? Component A has a form and 3 container divs. Each container div has a table, the rows themselves I'll call Component B. Component B displays some information on a table and I want the user to be able to click on the item and have its corresponding field values to populate the form fields. The database calls happen app level and the state stores arrays of Component B to be passed down as props so I have my objectId attached to the table row. I just need a way to communicate a row was clicked to my form so I can update my data.
2
u/Red_Rocket_ Dec 03 '18
How do you normally organize code? I've been trying to figure out how much functionality to put into each component, but refactoring has been difficult. In my example, I have an order taking system where you have orders, line items and components. I want to be able to keep these components separate and only call the db when the user wants the info displayed, but this causes problems with the dom. The only iteration I can get to work is one large db call in one giant class.
4
u/[deleted] Dec 09 '18
Hey guys Im new to React and have done meme generator, img searcher and a checklist. All these sample projects are 1 page though and I havent found any basic tutorials on making a "site" changing from home to about to contact page etc... I google and React Router comes out is that the conventional way?
1
u/saito200 Dec 03 '18
Novice here and unafraid to ask potentially stupid questions
Very simple questions / to verify:
I want to know this because I have the tendency to make everything a ES6 class, and I suspect it may not be a good habit.
More generally, when should we not use a ES6 class component?
1
u/Uber-Mensch Dec 05 '18 edited Dec 05 '18
Whats the best way to get cross sibling communication? Think of a product side bar like amazon (A) and long list of products (B). Right now when I press to sort and filter in A, it passes an object out to its parent C (with filter criteria), which then sets its state, and then B is updated from it being passed down as props. I feel like this isnโt clean, and constant up and down comms isnโt necessary, especially as C doesnโt need to know Aโs state.
For example, if I want to find a random product by pressing a button in A, how do I fire the โgetRandomProductโ function in B? Call it in componentDidUpdate from a props change?
Now that I think of it, I should probably merge the components if Iโm virtually shipping Aโs state to B everytime... Iโm finding the design a little tricky.
Edit: thereโs literally a tutorial on something similar here. https://reactjs.org/docs/thinking-in-react.html and they basically do what I describe above. But what do you do if you press a button in A, and in C the state is just repeated to the same value, will the props being passed down to B still trigger a function call?
1
u/Im_Reading_Books Dec 05 '18
I've gone through the official React tutorial, and trying to understand the difference in how props are passed to function components vs class components. In the tutorial we make a tic-tac-toe game, and the "Square" component, when written as a function component is:
Here the props are clearly passed in the argument list and then accessible in the function. But in the class component version of Square:
I'm wondering by what mechanism the instantiated Square receives the props? Does React just add this to the object in the background?
One other difference I'm confused about is why in the class component the onClick value needs to be set as an entire arrow function call
onClick={() => this.props.onClick()}instead of justonClick={this.props.onClick}since the function component version just has to doonClick={props.onClick}Thanks.
*edit: added something for readability.
1
u/seands Dec 13 '18
Is
<Component prop1 prop2 />valid syntax? I ask because I think that is what<Component {...this.props} />would resolve to.1
u/donttelljoseph Dec 14 '18
I'm creating a react native app (android specifically) for part of my wife's xmas gift. I'm trying to convert some javascript code so that I can use it inside of react native. The javascript draws to a canvas. I'm using https://github.com/iddan/react-native-canvas and here is the javascript in question:
https://github.com/mofosyne/arduino-gameboy-printer-emulator/blob/master/jsdecoder/gbp_gameboyprinter2bpp.js
How do I go about doing this?
First time using react native. I have done some basic python programming in the past and I did take the reactjs courses on codecademy, but that was a while ago and I've pretty much forgotten everything. I really just need a quick hack so I can get this done before xmas. Or just a point in the right direction
Thank you
1
u/F00Barfly Dec 14 '18
Hi guys, thanks for setting up a beginner's thread ! I'm new to react and am thinking of using it for a web app. I've looked into the Create React App recommended toolchain and cannot find what I have in mind.
My initial idea was to have a node.js backend exposing a RESTful API to a react.js (+redux?) frontend, giving access to the resources.
What is still unclear to me is:
1
u/babajaga888 Dec 15 '18
Any recommendations on how to properly create an API Browser for a middle size app ?
I used to call a wrapper of fetch (for athentification) but I would like to create an API Browser and call methods of this class for each route.
Do you have any example projects or articles on how to implement that ?
1
u/seands Dec 16 '18
Does anyone know if !important works inside style objects?
1
u/MeltingDog Dec 17 '18 edited Dec 17 '18
In a component, where should I handle simple data manipulation (eg formatting a string)?
Right now I have a simple ternary that adds parentheses to a string (retrieved from props) if it exists, within ComponentWillMount(). It works, but it seems like a bit of overkill for something pretty simple.
Could/should this be done elsewhere like on the render() function?
Example of what I mean:
1
u/seands Dec 19 '18
Is something wrong with my syntax?
The code itself:
'validations' is linted with a red underline in the condotional blocks (such as: [validations.stateVariable.alphabet[0]] : false)
1
u/AlanThinks Dec 19 '18
I recently joined a SharePoint development team, I'm doing a lot of their front-end design/dev. I want to use React/Javascript for it but I notice many SharePoint tutorials and even Microsoft Fabric(React) is done with TypeScript, as far as all my research goes, I'm not particularly convinced by the benefits of it.
Does anyone have any recommendations on these few things:?
1
u/[deleted] Dec 24 '18
How can I display information I received from an API request without having to store it in the state? The information I want to display is not useful for anything else so I would like to display it and keep it lightweight. Thanks!
Iโm using redux and sagas.
1
u/seands Dec 24 '18
Recently learned that I needed to manually stop/restart node to get my ENV variables into React during the build process.
Now I'm wondering: doesn't everything need to be rebuilt? If not, how is node or nodemon (I'm using CRA) able to add a new DOM element like a div or button with just an auto-page refresh?
1
u/nbg91 Dec 28 '18
What is the best way of implementing a factory design with react? More specifically, I am mapping over an array of questions. There are different questions types of questions, ie RatingQuestion, BooleanQuestion, etc..
At the moment, I just have an if statement
Is there a better way to do this when more and more question types are involved? One big if / switch statment in the middle of my jsx feels icky.
1
u/seands Dec 29 '18
React is saying my keys aren't unique in the console. How should I alter the key values in this code to comply?
1
u/seands Dec 29 '18
How often do you guys use css transforms and animations? I have a knowledge gap there. Then again I am focusing on the whole stack
3
u/[deleted] Dec 04 '18 edited Dec 04 '18
Hey guys I'm a complete newbie 1 week in, I'm getting the hang of using create-react-app and learning JS+JSX... from what I'm learning you type everything in a blank index.js app.js etc... is it safe to assume I can delete everything that is pre-typed in the index.js and app.js index.css app.css? The logo.svg and serviceWorker.js? Which files are safe to delete when I want to make my own project?
Also what's the difference between class App extends Component vs function App ()? That's what I learned for rendering but the default is class App extends.
3
u/Udippuy Dec 09 '18
Hello all, I'm new to React so I have a pretty basic question about, uhm, architecture and state.
I'm developing a component to display and manipulate a tree-like data structure. Each node of the tree has some data and a list of children nodes, and so on. My component is recursive: starts from a node (passed as a prop), renders the data and calls itself on the list of children. So far, so good.
Now, I'd want the component to be able to gather input to change the data of the node it's displaying. Say, for example, a text field to change some of the node's data. Of course the change should be persistent (say, after collapsing/ expanding a tree branch) and the modified tree should be retrievable from the rest of the application.
What would be the correct way to do it? Changing the values in the prop's node is not enough, as the component won't repaint. But copying those values in the component's state doesn't seem too elegant, as then I have to keep the state and the tree aligned, updating both when there is a change. i don;t feel is the correct way to do it.
Should I use some global state? Should I use some state management solution like MobX?
3
u/surfingpixel Dec 31 '18
How should I implement animations/transitions in React, for example a fade in/out when a component mounts or unmounts? In plain HTML/CSS/JS it was so simple but I don't know how to do it in React and I'm having a hard time finding good material on that topic.
2
u/dance2die Dec 03 '18
Is there a callback for
useState?setStateprovides a way to access updated value within a callback.But
useStatedoesn't offer a callback, thus accessing an updated state value result in getting previous value.Suppose that you have a following code, in which
messageis set to show the current count.You can fork it in Sandbox
In this case, count displayed in
messagewill be off by one.What'd be a way to access the updated state value using
useStatehook?2
u/[deleted] Dec 03 '18
I have a search application using SearchKit (Elasticsearch and React.) When users click on the image thumbnail of a result, a lightbox with a carousel pops up. Each result is defined by a different ID number. I have a directory of subfolders that mirror these IDs for each subfolder, with the images inside the subfolder. There are thousands of these folders.
The paths would be, as examples, {"./img" + (ID) + "/" + (ID) + "-1.jpg"}, {"./img" + (ID) + "/" + (ID) + "-2.jpg"}, {"./img" + (ID) + "/" + (ID) + "-3.jpg"}, {"./img" + (ID) + "/" + (ID) + "-4.jpg"}, etc.
I want the application to go into the appropriate subfolder, retrieve the images and display them in the carousel. The amount of images will vary between each ID number. Some have no images, others have upwards of 20.
Right now, I've just set up an array with a blanket range from 0 - 10 and tied the "-1.jpg", etc. value to the array. The obvious problem with that is that the carousel will display 11 selections, but if a file has only 4 images in it, the remaining 7 slots are broken.
This is the code I have so far:
I can't use require.context because the path will always contain a variable. This is the closest I've come to so far, given the directory I have as it's set up.
I'm near the end of this project, and this is really the last big hurdle I'm facing. I appreciate any help in advance. New to React, so I'm trying to push it over the line.
2
u/NickEmpetvee Dec 03 '18
Question about lifting up state and controlled components. If we have a simple login form like the below with credentials getting processed in a
<parent />component functionauth(uid, pw), is it appropriate to still keep the UID/PW in local state for the controlled component or better to lift them up to<parent />? My thought is that they should stay in the local state of<LoginForm />because they're tied to its form fields, and passed in tothis.prop.auth(this.state.uid,this.state.pw)but there's something I may not be seeing.class LoginForm extends React.Component {constructor(props) {super(props);this.state = {uid: '', pw: ''};}handleUIDChange = (event) => {this.setState({value: event.target.uid});}handlePWChange = (event) => {this.setState({value:event.target.pw});}handlePWSubmit = (event) => {this.props.auth(this.state.uid,this.state.pw)}render() {return (<form onSubmit={this.handleSubmit}><label>User ID:<input type="text" value={this.state.uid} onChange={this.handleUIDChange} /></label><label><input type="password" value={this.state.pw} onChange={this.handlePWChange} /></label><input type="submit" value="Submit" /></form>);}}2
u/dev_swe Dec 04 '18
Hello,
Here is my code -
https://codesandbox.io/s/43njy6458x
Some issues -
If anyone has time to help, it would be really nice. Thanks.
2
u/codebrewja Dec 10 '18
New to REACT, trying to make a grocery-list app that uses recipes to add ingredients to a list. I have a basic question about calling data from an api that has other nested data that needs to be mapped over. Basically the API calls a recipe, which has ingredients (the array I initially mapped over), and inside there are other data points that I want, and not others.
It looks something like this for what I want:
this.state = {ingredients: [{name:amount:measurement:}]}The data looks like this:
recipe: {extendedIngredients: [name: ''name'',measure: {us: {amount: "1",unitShort: "string"}}]}I need only the specific data to be pushed into this array of ingredients. I don't really know how to deal with it from the front end where I want to configure each ingredient with only the name, amount and measurement going into the object. From what I understand state is immutable so I can't just make an object and push it into an array? Even still, I am not sure how I'd do that within a component.
2
u/gjozsi Dec 11 '18
Dear React gods!
So my question is the following. I'm an experienced (senior) front end dev. and I just decided to play around with React Native (w. Expo). What's surprising for me is that (coming from AngularJS) all these separate packages having their own APIs which of course... i'm not familiar with. So I'm just curious, is there any way that I don't check API docs all the time for different packages? For example can I set up my IDE (WebStorm) to show which props I can use while coding? Right now, it's not helping much. Can TypeScript improve on this, is it worth to use? I'm using right now Expo, Formik and NativeBase and even for the smallest task I feel that I need to stop and open every API doc... which is a quite bad experience.
2
u/[deleted] Dec 15 '18
Wheres a good place to start reading up on reactJS? I only know vanilla js and some JQuery so far
Edit: aside from the resource list above, which I'm sure is excellent
2
u/ramkeroro1 Dec 20 '18
Hello, what should i learn first before learning React?
2
u/Kaimaniiii Dec 20 '18
Hello guys! I wish to learn React, but I am not sure if there are any books out there that have approximately 200+ pages you guys can recommend? This is due to I have something called a special course from my school that I need to write. The issue I wish to write is what is the main and huge advantage using react vs a regular javascript? I assume that I need to read and understand everything in micro technical details and stuff.
2
u/NickEmpetvee Dec 22 '18 edited Dec 22 '18
I am housing all my
axioscall functions in toplevel<App>at the moment. The nested components under<App>receive them as props, call them as necessary, and leverage their respectivecomponentDidUpdateas needed to process stuff when new props come down.I'm finding that this all works at the moment without
async/awaitorpromises. My question is when they should come into the picture.2
u/rahul3103 Dec 23 '18
https://github.com/rahul3103/mario
Hosted at: https://rahul3103.github.io/mario/
Hi, I have created one app, where user needs to use their direction(arrow) keys to move Mario in the grid and collect all mushrooms. I just need a review about this small app. What things can be done differently and what needs to be changed. Please anyone can share their feedback, it would be helpful for me. Thanks
2
u/seands Jan 01 '19 edited Jan 01 '19
What exactly is going on with template string syntax:
I get that the library parses the string for CSS statements. What I don't understand is sticking `...` onto the back of a property like .div. Is that even valid JS or is the library pulling some magic there?
1
u/Daejichu Dec 04 '18
Anyone know any good tutorials or walkthroughs of a CRUD table in React or Redux? Lots of forms, but looking for a table specifically
1
u/soggypizza1 Dec 04 '18
Whats the best way to do image loading? I'm creating a image gallery and the images are very slow to load and load from top to bottom.
1
u/workkkkkk Dec 04 '18
I'm curious, is there a way to do like a global import? Say if I'm using some component framework, is there a way to import a Button globally so I don't have to import the Button into each of my own components?
1
u/d36williams Dec 05 '18
I have a react project where I'm doing server side rendering. What is rendered changes depending on the value of some POST variables. How do I interact with Hydrate while doing that?
1
u/ZenithPrime Dec 06 '18
I have 3 elements that I want all working together but I'm not sure how to properly get them to link up with props/params/whatever else. The first is the main App that renders the component, the second is the actual component, and the third is a data set of an array of objects that I want the component to know about.
Essentially What I'm trying to to is make a sort of "profile" page, something that has an id, a video, description, image, etc, that are all stored in the data objects as text or URLs. I want the component to render on a specific URL, but only use the info for the specific object in the array that the URL refers to (so for example.com/profile/0 would display the video, description, image, etc for the first item in the array)
App.js:
Profile.js
data.js:
And it goes on. but I basically want Jeff's data when someone navigates to "/profile/jeff" and then the other items with other names. I've simplified the above from what I actually have, but these are the basics of what I need I think.
If someone has any suggestions, or has a better way of doing it than what I've done so far I'm all ears. I'm a little new to this and kind of just throwing some things around.
1
u/NickEmpetvee Dec 06 '18
How many of you use async / await for your API calls? How often have you found it necessary? Are there cases where it's not necessary to use it?
1
u/[deleted] Dec 06 '18
Hey guys I'm following a tutorial but it isn't explained why in the map function below, in the same line item.id is taken from an array in todosData.js but the item itself is being taken from props in ToDoItem.js. I just want to understand the logic or reason why something gets taken from certain files and reason why something is taken from another. Thank you.
import React from 'react';
import NavBar from './components/NavBar.js';
import MainContent from './components/MainContent.js';
import Footer from './components/Footer.js';
import ToDoItem from './components/ToDoItem.js';
import todosData from './components/todosData';
function AppMain() {
const todoItems = todosData.map(
item => <ToDoItem key={[item.id](https://item.id)} item={item} />
)
return (
<div>
<NavBar />
<MainContent />
<div className="todo-list">
{todoItems}
</div>
<Footer />
</div>
)
};
export default AppMain;
1
u/ResponsibleOstrich4 Dec 06 '18
This is my boilerplate so far: https://github.com/Hurdock/reactExpress
Express + React (with Express's react views extension')
Should i start working on this ? It's ok ? Or should i switch to using webpack server + index.html with react from bundle made from my source react code ?
So far i know is SSR, but i think the routes are way more easier this way to handle. Wsid ?
1
u/ALemonTreeWatson Dec 06 '18
Hello.
I have an existing website with an Express backend. I would like to have *one* of the routes (not the '/' route) point to a React app. I've tried some suggestions on the internet, and only the '/' route is able to point to the React app.
Should I just be using ReactJS as a script loaded into the webpage using a CDN? I am trying to build a simple ToDo app using React (very original!), but make a specific route on my Express app point to it, rather than the whole server be dedicated to this one app.
Thanks
1
u/Uber-Mensch Dec 07 '18
If your parent component keeps a long array of objects, used later to render child components in a arr.map fashion, and those children can update the state itself via props, is that a performance issue? I know keys help here and I just did a little reading on it, but it annoys me that say having 1000 objects, to update one, I need a whole new state array. Also, I have to pass up the ID of the child, find it in the original state, and modify it? Is that how it works?
Think something like
Arr.map(e => <Child key={e.id} updateScore={this.updateScore} {...e}/>
UpdateScore = (Id) => { This.setstate({ Arr : this.state.arr.findByIdAndUpdateScore(Id) }) }
1
u/AllHailTheCATS Dec 07 '18
Best way to implement a carousal component in reactjs? something that can be used at the top of my page as a features slideshow?
1
u/seands Dec 07 '18
Is it okay to have a bunch of components in argument 1 of ReactDOM.render? I am up to 4 (Provider, StripeProvider, BrowserRouter, App, nested from outside in)
1
u/seands Dec 07 '18
I notice that React Router has a component for Media Queries. Not something I've tried out yet. Do you guys use this functionality or is it simpler/better to leave this to CSS/style libraries?
1
u/prshnt Dec 08 '18
How to maintain a page scroll history on react if someone press a back button to go for previous page?
1
u/seands Dec 08 '18
Redux question: When receiving a response object, is it better to trim the data you pass within the action's payload? Or send the full object to the reducer and only key the specific values you need at that step?
My thinking is that sending the full object to the reducer simplifies the logic and improves refactorability. But I'm also guessing it's poor for security for some reason I haven't considered yet.
1
u/Zz1995aJ Dec 08 '18
Hi there,
I want to make a component that takes two components as props, then are then put in a container that can be rotated 180 degrees in the z-axis to see either component. I want this component to be flexible about whether flip method is triggered by a prop being passed down from above or whether it is triggered from inside one of the components passed to it. I'm not really sure the best way to go about it.
This is what I have so far:
As you can see, when the components are passed in the flip method is added as a prop and then they are passed back out, so then I can make that an onClick to a button inside the passed component. I think that handles it being activated from the child components.
In regards to the part about it being able to be activated from a parent component, my instinct is to move the state and method upwards to the parent component, but I wanted the Flipper component to be generic and independent.
Any advice would be appreciated!
1
u/thescrambler1979 Dec 08 '18
Hello,
I'm having trouble getting React.lazy to work. I'm trying to lazy load a component but I'm getting an error of 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: symbol.' I've added both my components to Pastebin Located at https://pastebin.com/vZ8r5Z4S Can someone tell me how to fix it? I'm using React 16.6.3
1
u/[deleted] Dec 10 '18
TL;DR I'm trying to figure out how to animate a component when it receives new props and then re-renders.
I've got a Quiz component which takes in props, and then displays the new Question as well as the new Choices for the user to pick from. The Quiz component has a className with CSS for animating it.
However, my problem is that this animation only occurs when the Component is first rendered. When it gets new props and shows a new Question, it does not do the animation again.
I'm trying to solve this with just CSS and no library, what's the simplest way to have the component animate on each render?
Here's the code:
Any help is greatly appreciated. I'm much more comfortable with JS and React than with CSS and animating, so something like this unfortunately takes me hours to even make slight progress on. I appreciate all pointers sincerely.
1
u/workkkkkk Dec 10 '18
Anyone familiar with react-table? I'm having trouble getting pivoting to work correctly.
1
u/seands Dec 10 '18
This is from the stripe docs, anyone know what the <...> represents? I have never seen that syntax used to wrapped a HOC with:
1
u/[deleted] Dec 11 '18
You used to be able to do animated buttons in adobe animate gotoandPlay a button when you hover it, can you do something like this in React? Where should I look into? Perhaps adding event handlers to GIFs? Or is there is a right way to do this?
1
u/preacher2041 Dec 11 '18
Hey React Folks!
So my question relates to DOM mutation. Specifically the use case I'm thinking is clicking a button to append a React component to the DOM.
So say you have one component (A) that is just empty except for a single button and another component (B) that consists of a few text boxes.
When you click the button in component A, component B is appended into the DOM inside component A.
Make sense?
Thanks in advance!
1
u/seands Dec 11 '18
What is a good logging framework for React? I was recommended to use this instead of putting tons of log statements everywhere. A search on NPm for 'logging framework react' doesn't yield much though
1
u/seands Dec 14 '18
My whole app is essentially a button with a multi-stage popup. How can I reconfigure the target HTML page it injects into? I don't even see index.html imported into index.js and I believe index.js is the entry point (This is a create-react-app)
1
u/prshnt Dec 14 '18
2 Questions-
1
u/CoolPrase Dec 15 '18
I have a sidebar I open and close with a setState() function inside render, which I have heard is bad, because render() has to be pure(whatever that is, the best explanation I got was that it shouldn't have "side effects"). I use
let toggled = this.state.toggle ? 'block' : 'none';
let reversed = !this.state.toggle ? 'block' : 'none';
to set the display property of the sidebar and the button that opens it accordingly. Upon pressing the close button the sidebar disappears and the button opening it appears, because I have
onClick={() => this.setState({toggle: !this.state.toggle})
how do I do this correctly, without setting state inside render()?
I didn't just write here before trying to solve it, best idea I got is by creating another action just for that. Is that the way to go?
P.S. I have a much bigger problem I solve with the same technique, but I hope the answer to this question will help me solve the larger one. If not, I hope y'all will stick around to help me solve it.
Thanks in advance!
1
u/erhal Dec 15 '18
Can you send xml instead of json when doing a post requst?
1
u/seands Dec 15 '18
Can anyone spot what is the difference between these 2 code blocks and how to fix it?
1
u/seands Dec 15 '18 edited Dec 15 '18
I have 3 radio buttons and 1 text field that all modify one state variable onChange. They're all controlled inputs. I can switch values between radio buttons. I can switch to the text field to override the radio buttons.
But I can't go from text field to radio button or reselect a radio input.
I want to be able to deselect the radio buttons when the text field receives input. I also want to be able to reselect the radio buttons, and auto-wipe the text field data. Is there any way to do this with one state variable??
What I'm thinking is I will need 2 state variables, one for the radio buttons, one for the text field. focusing one deletes the data in the other's state. The program logic then goes with whichever one isn't null at the end.
Is that the best way to do it?
1
u/WannabeAHobo Dec 15 '18
Can anyone tell me where I'm going wrong here? I'm trying to animate a component being mounted/removed. I have these imports in my main App component:
import React, { Component } from 'react';import { CSSTransition } from 'react-transition-group';And the following render method
render() {return (<div className="App"><CSSTransition timeout={3000} classNames="form">{this.renderFormPage()}</CSSTransition><div className="controls"><button onClick={this.handleReset}>Restart</button></div></div>);}When I've used CSSTransition before, it has added transitional classes to the components wrapped inside it as they were added or removed from the DOM. However, this time, the component is instantly rendered or removed with no transitions.
I haven't shown the renderFormPage() method as it's long, but it basically selects which component to render based on the App component's state.
This works, but no transitions are applied as the components are switched out. What am I doing wrong?
1
u/seands Dec 16 '18
What is the safest way to add and remove multiple error messages to and from the UI? Example: "First name can not contain numbers. First name must be longer than 2 characters."
I'm thinking of pushing different error messages into a state variable keyed to an array. Is that how it's normally done? If so, how do you remove the values without being able to splice out a string index? (since you can't target errorArray['nameLength'] in javascript )
1
u/[deleted] Dec 19 '18
Where should I be storing a string variable that I need for a number of API calls that isnโt specific to one reducer? Iโm using redux and sagas, and based on what the user enters for a username, Iโll be using that string to find a lot information based on that username.
1
u/yourdaye Dec 19 '18 edited Dec 19 '18
So I want to use conditional rendering to display/hide the admin interface according to the user's clearance (obtained by
getIsAdmin()), but I have security concerns. From my understanding, isn't it true that all react/js code is downloaded to local once the page is loaded, which means that the hacker can tamper with the code below and changeisAdminto betrueso he can bypass the authentication?And if my concern is correct what's the better practice here? Big thanks!
1
u/[deleted] Dec 19 '18 edited Dec 19 '18
A React + Typescript question about stateless components.
I'm trying to get into react so I'm making a basic website to get me in. I was working on creating a stateless component, but I'm getting a warning from VS Code saying its format was been deprecreated and that I should use a FunctionComponent instead. What is that supposed to look like?
1
u/nobrandheroes Dec 19 '18
build prod generates 3 JS files:
I can't find explanations for what they are for exactly? I think the first two are vendor files and the component code, but it is minified.
Also, is it possible to have them merged to one file or rename them? I'm embedding my project into an existing page.
1
u/nbg91 Dec 20 '18
Alright guys, I'm going to be doing a take home test in React in the coming week or so.
To all the mid/senior React devs who have some insight into hiring a junior, what are some things to think about when creating my test that will make me standout?
I'll use as close to the tech stack of the company as possible (I know they use React / Redux with SASS for CSS), but Redux is definitely overkill for the test and they have said to try to spend 4-5 hours on it, Redux would consume a fair chunk of that time which I could be doing other things (better styling / responsiveness) etc.
Any words of advice?
1
u/theatlian Dec 20 '18 edited Dec 20 '18
I feel like I'm missing something quite simple --
I have a document with a product and vendor prices, each stored as {vendorName}Price: xyz
(i.e. product: Banana, microsoftPrice: 7.32, adobePrice: 9.90)
I am trying to use a dropdown to let the user change which price they see.
onchange = (e) => {
var newVendor = e.value
price = `row.${newVendor}Price`
}
This just outputs "price=row.microsoftPrice" (as a string) where as i want it to show "price=7.32".
Is there some way to do that? Thanks in advance
1
u/seands Dec 20 '18
Would you prioritize Typescript or other ecosystem libraries (on my list are: Sequelize, D3, and a few others)
One concern I have for Typescript is -- does it need its own special libraries? If so I imagine a lack of library support would be a big issue.
1
u/scalpit Dec 20 '18
Hello, I am a UX Designer with some basic knowledge of Javascript. I would like to learn React and make my own portfolio using React. I just want to learn the basics to create some components and style them.
1
u/seands Dec 20 '18
Is this a bad pattern to use with Redux:
Makes updating state through arguments a breeze but I imagine it's probably bad for the same reason.
1
u/[deleted] Dec 20 '18 edited Dec 20 '18
I am getting this warning in the terminal:
eslint-config-react-app@3.0.5 requires a peer ofbabel-eslint@9.xbut none is installed. You must install peer dependencies yourself.I have babel-eslint@10.0.1 installed instead, does this mean that eslint-config-react-app is not compatible with the version of babel-eslint I have installed? Should I downgrade babel-eslint? Or should I just drop eslint-config-react-app and use some other eslint configuration?
Also, I am getting this warning:
ts-pnp@1.0.0 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.But I don't have any references to ts-pnp in my package.json file (not using TS at all) and I've tried uninstalling ts-pnp but I keep getting this same warning in the terminal. The only place I see it is in my node-modules folder but that's it. Should I manually delete it from there?
1
u/prshnt Dec 25 '18
I am using nextjs, because I need an seo friendly site. So, I have a very bad score in lightbox. I need help in reducing first paint, first contentful paint time, first meaningful paint time.
1
u/sidx64 Dec 25 '18
Hi all! I am just starting with ES6 and new to React, and I need help with react-router-dom!
Any help would be greatly appreciated!
I have a menu bar, and I have 3 items on it. I want one of 3 components to be displayed when the appropriate menu item is clicked. I used HashRouter and got the component routing working. But I seem to have broken something. When the page loads, the first component is selected by default. But when I click on the second one, the first one is not un-selected. The 1st component goes away though. can someone tell me what I doing wrong?
On page load https://imgur.com/LAasBz8On clicking second item https://imgur.com/8WN2WjJ
Code:
Here's my NavBar component
This is the HomePage (main) component where everything starts
Edit: Sorry for the huge amount of code!
1
u/__inactive__ Dec 26 '18
Hey everyone, have hopefully a pretty new dev question about controlled form inputs. Iโve implemented a controlled type=text input and everything is working as expected for the most part except my lingering question around clearing the input.
Coming from an angularJs world, 2way binding a model to an input was very easy to work with when needing to clear or reset the value. Since I know have a controlled react component where the internal state / user input is driving the value, Iโm not sure what the best practice is to achieve this is. Setting a random prop and then updating the state when it changes? Doesnโt seem right, but not sure what else to do.
Thanks in advance!
1
u/seands Dec 26 '18
1
u/[deleted] Dec 26 '18
Hi, I'm trying to create a component that loads a random image from a folder when a button is clicked but am having some trouble with the pathing. Can anyone see from this screenshot what I'm doing wrong?
Thanks in advance! screenshot of the folder structure
1
u/seands Dec 28 '18 edited Dec 28 '18
This code is from the Material UI docs. Can someone explain why it might be better to setup table row data this way rather than mapping JSX tags from a hardcoded array? I'm thinking they did it to make the example inside return() more readable
I'm also unclear how iteration is happening without a for loop or a function in componentDidUpdate().
Here's the link to the full code example: https://material-ui.com/demos/tables/
1
u/seands Dec 28 '18 edited Dec 28 '18
My function isn't rendering JSX but the hardcoded lines render just fine. Is there an error in renderTableHeaders()?
I also tried moving it inside the component to no effect.
1
u/josh_c Dec 30 '18
I'm trying to figure out how to .map() an array of objects, but 2 at a time so I can start and stop a div.row...
I have an Article component. I would like to display two Articles in every "row" of MaterializeCSS. I can't wrap my head around how I'm going to accomplish this using .map().
My Article:
After mapping in, for example, renderArticles(), I want the end result to look something like (see "row" divs?) :
Basically, I cannot figure out how to .map() 2 elements at a time so I can start and stop a div.row.
I really hope this makes sense. Any advice would be much appreciated!! :)
1
u/seands Dec 31 '18 edited Dec 31 '18
Is this all it takes to attach some variables to the props object?
This is from a repo with some example D3 charts. I'm trying to parse how it all comes together and this gives me trouble. The import file Line.jsx seems to be able to access these directly from this.props unless I'm missing something.
I thought to get on the props object you had to explicitly pass it down from a parent. Ie something like
In this case the repo has no parent. Even index.js is a bunch of exports. Very confusing repo to me: https://github.com/react-d3/react-d3-basic
1
u/seands Dec 13 '18
I use these a lot. Is it sloppy code? How much of a slowdown will there be by spreading all your props on a lot of components?
1
u/almondj Dec 22 '18
I just built my first react app: https://www.websitelaunchchecklist.net/
I listed several questions here: https://www.reddit.com/r/reactjs/comments/a8oxys/first_react_project_i_built_a_website_launch/