Stefan Stefan - 21 days ago 6
React JSX Question

Reactjs sending prop to child that is handed from Route

I have a following render function in my top most component App:

render() {
const { content } = this.props;
return (
<div id="content">
{content}
</div>
)
}


The {content} variable is delivered from Routes like this:

export default (
<Router history={History}>
<Route path={UserConstants.HOME_ROUTE} component={App}>
<IndexRoute components={{content:HomePage}}/>
<Route path={UserConstants.LOGIN_ROUTE} components=}{content:LoginPage}} />
</Router>
)


How can I add props from the parent App to the {content} ?

Answer

In App, instead of {content} use

{React.cloneElement(content, {
     myProp: 'value'
  })}

And myProp will be accessible in the child component in this.props.myProp .

You can make this more dynamic to work with different child components if you use

{React.cloneElement(this.props.children, {
     myProp: 'value'
  })}