Most React apps I build are self-contained - the entirety of the app lives within a root component, and is responsible for rendering the full web page/app. And the app doesn't need to communicate with other JavaScript or elements on the page.
But in some cases the React app is a page/app add-on, responsible for rendering only a small part of a web page/app. Some examples - widgets, forms, maps.
In many cases these widgetized apps are self-contained and don't need to communicate with the rest of the web page or app. But occasionally they do... and some setups require the state and methods within a React component to be accessed from outside React.
Is this possible? And if so, how?
How To Access Component State/Methods From Outside React
Consider this simple setup:
<div id="app"></div>
<button id="button">Get App State</button>
Let's say our React app renders a root component of OurComponent
to the #app
element. Then, a click
handler on the #button
should display the state
of OurComponent
.
The Old Method
The old recommendation, which still works, was to assign the return, a reference to the root ReactComponent instance, from ReactDOM.render()
to a variable. This reference could be used to access methods on the component. Like this:
const ourComponent = ReactDOM.render(<OurComponent />, document.getElementById("app"));
ourComponent.someMethod() // would call the method
However, according to the React docs, "this return value is legacy and should be avoided because future versions of React may render components asynchronously in some cases."
The New Method
As an alternative to assigning the return from ReactDOM.render()
to a variable, the docs state "the preferred solution is to attach a callback ref to the root element."
To do this, add a ref
callback and assign the DOM element as a global variable. The ref
callback receives the underlying DOM element as it's argument, so we can do the following:
ReactDOM.render(<Page ref={(ourComponent) => {window.ourComponent = ourComponent}} />, document.getElementById("app"));
which allows us to access OurComponent
with window.ourComponent
, and methods of the component can be accessed with window.ourComponent.someMethod()
.
An Added Bonus
One advantage of this method is it allows us to create a reference to nearly any component in our app, not just the root component. This means we can interact with any component, root, or child, from outside of React.
Here's a quick example showing how we can access the state of 2 components - a parent and child, from outside React.
See the Pen Accessing React Component Methods and State from Outside React by Brett DeWoody (@brettdewoody) on CodePen.
Comments