Ad

Update React Component Without Parent Outside Of It

- 1 answer

How should I properly update component if it doesn't have a parent?

I've found two ways to do it:

First method

Here I update component through changing component`s state:

var Hello = React.createClass({
  render: function() {
    if (!this.state) return null;
    return (
      <div>Hello {this.state.name}</div>
    );
  }
});


var component = ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);
component.setState({name: "World"});

setTimeout(function(){
  component.setState({name: "StackOverFlow"});
}, 1000);

Second method

Here I update component through ReactDOM.render method:

var Hello = React.createClass({
  render: function() {
    return (
      <div>Hello {this.props.name}</div>
    );
  }
});


ReactDOM.render(
  <Hello name="world"/>,
    document.getElementById('container')
);

setTimeout(function(){
  ReactDOM.render(
    <Hello name="StackOverFlow"/>,
      document.getElementById('container')
  );

}, 1000);

So which method is correct? Or maybe here is a third, correct way?

Ad

Answer

If you simply want to trigger a re-render from outside the component, its forceUpdate method is exposed.

The initial ReactDOM.render returns a reference to the component, which you can use:

const component = ReactDOM.render(<MyComponent />)

component.forceUpdate()
Ad
source: stackoverflow.com
Ad