Green
Green

Reputation: 30865

How to pass props to components when you use <Route components={} > attribute?

So, the <Route> component of react-router has components attribute (docs):

<Route path="latest" components={{sidebar: Sidebar, content: ContentLayout}} />

Then in an appropriate component I can call those components through component's props:

render() {
    <div>
        {this.props.sidebar}
        {this.props.content}
    <div>
}

However without react-router I would do this, I pass my component custom props:

render() {
    <div>
        <Sidebar names={ ['foo', 'bar'] } isOpen={true} num={10} />
        <ContentLayout type={ contentType } background={'#fff'} title={titleOne} />
    <div>
}

My questions is. How can I pass props to my component when I use components attribute of React Router <Route> component?

The best way would be something like this:

render() {
    <div>
        {<this.props.sidebar names={ ['foo', 'bar'] } isOpen={true} />}
        {<this.props.content type={ contentType } background={'#fff'} />}
    <div>
}

Upvotes: 0

Views: 175

Answers (1)

Horia Coman
Horia Coman

Reputation: 8781

One solution for this is to clone the components and specify new props for them in the cloning process. Something like:

render() {
  return (<div>
    {React.cloneElement(this.props.sidebar, props={names: ['foo', 'bar'], isOpen: true})}
    {React.cloneElement(this.props.content, props={type:contentType, background: '#fff'})}
  </div>);
}

Upvotes: 1

Related Questions