0
votes

I can't rerender the parent component from the child component - I pass componentDidMount as props to child class, then I call it there, and expect the parent to rerender. The render function is called, but the content remains unchanged. What's wrong?

var Parent = React.createClass({
   getInitialState: function () { return {content: 'clean'}; },
   componentDidMount: function () {
      this.setState({content: 'changed!'});
   },
   render: function () {
      return React.createElement('div', {rerender: this.componentDidMount.bind(this)}, this.state.content);
   }
});

var Child = React.createClass({
   render: function () {
      return React.createElement('div', {onClick: this.handleClick}, 'click me');
   },
   handleClick: function () {
      this.props.rerender();
   }
});

ReactDOM.render(
        React.createElement(ReactRouter.Router, {history: ReactRouter.browserHistory},
                React.createElement(ReactRouter.Route, {path: '/parent', component: Parent})
        )
, document.getElementById('content'));
2
send a class method as prop callback to child component, the callback needs to setState in the parent component - Daniel Lizik
But thats exacly what I did in my example - user99999
don't use the this.componentDidMount as an event callback :) you should create own function to handle that rerender in parent component.. and of course it won't chance since when the parent component mount the state will be content: changed! and when you handle click it will call that same function so state will be the same.. - Hardy
Yes, yes, I know, I just gave an example ;) Thanks! - user99999

2 Answers

0
votes

componentDidMount() is a lifecycle function called when the component has completed rendering.

Calling it is seeming like you are circumventing the entire rerendering process.

You should instead create your own function.

   changeContent: function () {
      this.setState({content: 'changed!'});
   },

And then pass changeContent() to rerender.

Generally, avoid passing React's LifeCycle methods around!

0
votes

To tackle all this kind of things, the guys at Facebook come up with unidirectional data flow pattern. Your child component should not know about the parent but rather it should change some sort of state (Flux, Redux, Reflux). Changes to the state will trigger rerendering of the parent component.