r/reactjs • u/acemarke • Oct 30 '17
Beginner's Thread / Easy Questions (week of 2017-10-29)
Looks like the last thread stayed open for quite a while, and had plenty of questions. Time for a new thread! (I should probably consider labeling these as monthly or something :) )
Soo... 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.
The Reactiflux chat channels on Discord are another great place to ask for help as well.
23
Upvotes
View all comments
Show parent comment
6
u/pgrizzay Nov 02 '17
There's a couple things that I would change to make your life easier:
1. Maintain your state in React
The most useful thing about React is that it helps manage your application state! The only caveat is that you have to let React know about your state, and work within its small API.
The
Formfieldcomponent is maintaining state outside of React. What you should do is come up with a json representation of your state, and store that state in React with thesetStatemethod.It basically boils down to 2 things:
setState.As an example, suppose the user has submitted 'pikachu'. In the
handleSubmitfunction, you'd do something like:This represents the state where your user has submitted a Pokemon to be found.
Now, what should your render do? It should return an
imgwith the found Pokemon (if there's a match)2. Bubble up your state to the highest common parent.
You're probably thinking... But I need the images rendered in another part of my app! In order to accomplish this, your state needs to be stored in a component that is a parent of both the component that modifies the state, and the component that reads the state.
So, that would look something like this:
where
this.handleSubmitis a function on your parent component that callssetStatewith your updated search term.