Frontend Developers: I'm redesigning DevTools. Want early access?

Update component state from outside of a React app

In some circumstances, you’ll want to update a component’s state or access its methods from outside of a React app.1 Luckily, React makes this easy. For instance, let’s say that we have a component called Foobar, and we want to update its state from somewhere outside of React:

class Foobar extends Component {
  this.state = {
    updateMe: "..."
  }

  render() {
    return <div />
  }
}

To enable this, we only need to add a ref prop to Foobar where we render it in the parent:

const App = () =>
  <div>
    <Foobar ref={Foobar => { window.Foobar = Foobar }} />
  </div>

Inside this ref, you’ll notice that we’ve assigned Foobar to the window object. This is important, because we can now access its state and methods from outside our React app:

// Somewhere outside the React app

Foobar.setState({ updateMe: "Okay I'm updating you!" })

console.log(Foobar.state.updateMe) // "Okay I'm updating you!"

Just remember that the component has to be rendered in order to access its state and methods. So if you have your app set up like this…

class App extends Component {
  this.state = {
    open: false
  }

  render() {
    if (!open) return false
    return <Foobar ref={Foobar => { window.Foobar = Foobar }} />
  }
}

…then App’s state.open will need to be set to true before you can access Foobar outside the React app.

Another simple solution. Thanks React!

  1. If you clicked on this article out of sheer curiosity, you might need this approach when running a React app alongside an existing one. For instance, I needed to use it to safely toggle a React-based Chrome extension. Another instance might be when a larger application slowly replaces its existing framework with React and still needs the app’s parts to talk amongst themselves. ↩︎

Frontend Developers: I'm redesigning DevTools. Want early access?