How should I properly update component if it doesn't have a parent?
I've found two ways to do it:
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);
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?
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()
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