Skip to content

Instantly share code, notes, and snippets.

@ArunMichaelDsouza
Last active December 27, 2017 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArunMichaelDsouza/cdf5e9f74ef24ab1130a982f37fd4a41 to your computer and use it in GitHub Desktop.
Save ArunMichaelDsouza/cdf5e9f74ef24ab1130a982f37fd4a41 to your computer and use it in GitHub Desktop.
Updating state of a parentless component in React
// DeeplyNestedChild.jsx
class DeeplyNestedChild extends React.Component {
constructor(props) {
super(props);
}
updateTopMostParent() {
// Call this method with the state value to update
window.updateTopMostParent(someValue);
}
render() {
return (
<button
type="button"
// Method to update the topmost parent
onClick={ this.updateTopMostParent.bind(this) }
>
Update TopMost Parent
</button>
);
}
}
// Parent.jsx
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
shown: true
};
}
render() {
return (
<Child>
<AnotherChild>
<DeeplyNestedChild />
</AnotherChild>
</Child>
);
}
}
// Store reference of topmost parent component
const TopMostParent = ReactDOM.render(<Parent />, document.getElementById('root'));
window.updateTopMostParent = (someValue) => {
// Update state of topmost parent when this method is called
TopMostParent.setState({ someStateVariable: someValue });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment