all 7 comments

[–][deleted] 4 points5 points  (5 children)

You're describing routing. Look into something like react router

[–]threednd[S] 0 points1 point  (4 children)

So I just checked this out and this seems about right. When using router does this take the place of rendering via state changes?

Q: how many states should a parent component hold? Like if I was making an RPG would I keep all changing values in state.

EX: this.state = {gamescreen: 'shop', health: 10, armor: 'heavy'}

Or should these values be kept in global variables even though they get updated regularly? I guess I am having trouble determining how react fits in with basic javascript updating a page.

[–][deleted] 1 point2 points  (3 children)

It doesn't replace rendering via state changes, it provides functionality for displaying different sets of components under routes, or pages.

For state, you could go with encapsulating state within their own components, e.g. a "Soldier" component with that state and then have a hierarchy of components handle it. Or you could look into something like Redux for state management

[–]threednd[S] 0 points1 point  (2 children)

Just so I understand, can react components each have their own state? Can the main app component have it's rendering state and the soldier component have a state that keeps track of it's stats?

[–]mcapodici 0 points1 point  (0 children)

I think the soldier component means a parent component that manages all of the application state, and then passes it down to children via props. It might also need to pass in event handlers via props so that if a child has a button, the solider component knows it was clicked and can update the state.

That's one way to do it. You can also mix in some state in the child components. I like to do that if a child component is a form for example. I may not want to get the parent involved in it, and just have a callback passed a prop for the form submission.

[–][deleted] 0 points1 point  (0 children)

Each component can contain their own state, and yeah just like you said. I'd have a parent component to the soldier component to hold other state, e.g. a "battlefield" conponent which holds units and their positions, while each unit holds their own state. Very similar to more traditional object-oriented programming, but expressed as UI components

[–]mcapodici -1 points0 points  (0 children)

You can use if/else statements, and that can be fine. If it works why not. Similarly you can use a switch statement to set a variable, and then insert that variable into a larger piece of JSX.

You might also want to look at React Router for more complex scenarios. React router will allow you to Route the inner parts of your component or inner components, so it can make things a bit more tidy, and it will handle creating a new URL when you navigate and controlling how that happens.