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!