ReactJS - Render With Default State

- 1 answer

How can I rerender component with state from getInitialState()?

For example:,output

In example code I click on the button, component Button change state and button is Yellow - its work, but when I click on another button I would like to clicked the button was yellow (its work), and the old button changed state and color to red (it doesn't work).



Avoid stuff like this:

childState.setState({klasa: "yellow"});

You should not be setting child state from the parent. State is internal to a component, it should only be changed by itself. Instead, the parent can re-render the child with different props.

If you want only one button to be active, then you have to have some piece of state that will only permit a single active button. Since children can't know about their fellow siblings, this piece of state must reside in the parent. I've called it activeBtn. If activeBtn is 1, then the first button appears yellow. This piece of state in the parent corresponds to the boolean property active in child. I've also defined a click handler in the parent to change the state. This click handler is passed down to each child as a prop.

If that doesn't make sense, the modified code should serve as a better explanation:,output