lightspeed
lightspeed

Reputation: 313

Passing data from child to parent, React.js

I'm trying to pass data from a child component up to a parent component. However, when doing so, I get the error:

Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount

I don't understand because when I use the same pattern with an event handler, everything is fine. How can I successfully pass data from the child component to the parent without getting the error?

const Child = (props) => {
  let message = 'Hi mom'
  props.callBackFromParent(message);
  return <h3>{props.message}</h3>
};

class Parent extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      messageFromChild: '',
    }
    this.callBackFromParent = this.callBackFromParent.bind(this);
  }
  
  callBackFromParent(dataFromChild){
    this.setState({messageFromChild: dataFromChild})
  }
  
  render(){
    return (
      <div>
        <h2>Message from Child is:</h2>
       
        <Child 
          message={this.state.messageFromChild}
          callBackFromParent={this.callBackFromParent}
        />
      </div>
    )
  }
}

ReactDOM.render(
  <Parent />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Upvotes: 1

Views: 3351

Answers (1)

Tholle
Tholle

Reputation: 112787

It's not allowed to call setState during rendering, which a call to props.callBackFromParent would result in.

You can use the function as an event handler instead, and it will set the state of the parent as expected.

Example

const Child = (props) => {
  let message = 'Hi mom';

  return <h3 onClick={() => props.callBackFromParent(message)}>{props.message}</h3>
};

Upvotes: 2

Related Questions