Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS updating state from child

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

like image 840
Yves Lange Avatar asked Apr 03 '14 08:04

Yves Lange


People also ask

Can we update parent state in child React?

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.

How do you update parent state from child functional component in React?

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.

Can we set state from child component React?

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.


1 Answers

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..."
like image 110
Ross Allen Avatar answered Oct 15 '22 17:10

Ross Allen