Skip to content

Instantly share code, notes, and snippets.

@bartlett705
Created November 4, 2016 00:35
Show Gist options
  • Save bartlett705/50e30a0f5eddcaeac29f076f505a886e to your computer and use it in GitHub Desktop.
Save bartlett705/50e30a0f5eddcaeac29f076f505a886e to your computer and use it in GitHub Desktop.

There are plenty of use-cases for single-page apps sharing elements of state between different views. Sometimes (often?) you might want those views to be distinct routes. For a small project, pulling in redux or another flux-like can seem like a bit much. So how can we share a set of properties that lives in state between our various view routes using React and React Router?

Let's say we have a routing component structure somewhat like this:

<Router history={hashHistory}>
  <Route path="/" component={Home} >
    <IndexRoute component={Profile} />
    <Route path="profile" component={Profile}/>
    <Route path="host/:eventId" component={HostApp}/>
    <Route path="guest/:eventId" component={GuestApp} />
    <Route path="createevent" component={CreateEvent} />
  </Route>
</Router>

In the parent route component (in our case, Home) that renders the relevant child path, instead of simply rendering <{this.props.children}> to pull in the view, we use cloneElement, like so:

{React.cloneElement(this.props.children, {
  passedprop1: this.state.prop1,
  passedprop2: this.state.prop2,
})}

This creates a copy of the react element in place of it's original version, and applies the props to it, so they will be available to the child componenet on, for example <this.props.passedprop1>, just as we would like!

The main disadvantage to this situation is that all child components must receive the same data, in the same shape. This rankles somewhat against the re-usable and composable intent of react architecture, and can be avoided with some slightly more complex react magic, which we will discuss next time!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment