Last active
December 27, 2017 18:47
-
-
Save ArunMichaelDsouza/cdf5e9f74ef24ab1130a982f37fd4a41 to your computer and use it in GitHub Desktop.
Updating state of a parentless component in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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