I'm using ReactJS with CoffeeScript (:
Actually I have a component A which handle a state. A state field is passed to the child (called myChild in that example). The child needs to update some value from the parent state.
How can I do that in the ReactJS way ?
A = React.createClass
getInitialState:
mystate: {test: 1}
render: ->
myChild {param: @state.mystate}
myChild = React.createClass
render: ->
React.DOM.div {onClick: @change}, @props.param.test
change: ->
@props.param.test += 1 # WRONG WRONG WRONG
ajax("/..../", JSON.stringify(@props.param))
.done(@onDone).fail(...)
onDone: ->
console.log "Hum..."
Comments:
[email protected] can't be changed like that (for coherence and it's should be immutable).
[email protected] is in fact the object inside the state of component A, thus it should be updated with @setState which is not possible since we are in the child :(
How can I clear this to have a good ReactJS component ?
Paul ? Will you still help me ? :D
To update the parent state from the children component, either we can use additional dependencies like Redux or we can use this simple method of passing the state of the parent to the children and handling it accordingly.
React hooks are introduced in React 16.8. If you are familiar with the class components then there is no difference to change the parent component state from child component. In both cases, you have to pass the callback function to the parent.
We can set Parent State from Children Component in ReactJs using the following approach. We will actually set the state of a parent in the parent component itself, but the children will be responsible for setting. We will create a function in parent to set the state with the given input.
The parent is the source of truth, so the child needs to tell the parent to change its state. Pass a callback from the parent to the child, and have the child call it.
There's an example on communicating between components in React's docs that might be helpful too.
A = React.createClass
getInitialState: ->
mystate: {test: 1}
incrementTest: ->
@setState {mystate: {test: @state.mystate.test + 1}}
render: ->
myChild {onChange: @incrementTest, param: @state.mystate}
myChild = React.createClass
render: ->
React.DOM.div {onClick: @change}, @props.param.test
change: ->
@props.onChange
ajax("/..../", JSON.stringify(@props.param))
.done(@onDone).fail(...)
onDone: ->
console.log "Hum..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With