So, I am rendering different components based on the URL using BrowserRouter and Route. But, There is a lot of markup which is similar while rendering. So, I have created a Wrapper which should take components as props and solve this!!
class Wrapper extends React.Component {
componentDidMount() {
this.props.setActiveTab(this.props.activeTab);
console.log('Wrapper props: ', this.props)
}
render() {
const OtherComponent = this.props.otherComponent
return (
<Row>
<Col md='8' id='content-block'>
<SwitchTab />
</Col>
<Col md='4' id='info-block'>
<InfoComponent info={this.props.info} {...this.props}/>
{
this.otherComponent &&
<OtherComponent {...this.props}/>
}
</Col>
</Row>
)
}
}
These are some of the Routes:
<Route
exact
path='/r/all/'
render={() =>
<Wrapper
setActiveTab={context.toggleTab}
activeTab={'3'}
info='all'
/>
}
/>
<Route
exact
path='/u/:username/'
render={(props) => {
return (
<Wrapper
setActiveTab={context.toggleTab}
activeTab={'4'}
info='user'
user={props.match.params.username}
otherComponent={Profile}
username={props.match.params.username}
/>
// <Profile username={props.match.params.username} />
)
}}
/>
<Route
exact
path='/r/:subreddit/'
render={(props) => {
return (
<Wrapper
setActiveTab={context.toggleTab}
activeTab={'4'}
info='subreddit'
otherComponent={Subreddit}
subreddit={props.match.params.subreddit}
/>
// <Subreddit subreddit={props.match.params.subreddit} />
)
}}
/>
The otherComponent is not getting rendered. I don't know where the problem is. Also if there is any other better method, please do state that.
You are checking if this.otherComponent is truthy before rendering. You just want to check if OtherComponent is truthy.
{OtherComponent && <OtherComponent {...this.props} />}
You could also change Wrapper to render children if you would prefer.
Example
class Wrapper extends React.Component {
componentDidMount() {
this.props.setActiveTab(this.props.activeTab);
console.log("Wrapper props: ", this.props);
}
render() {
const { children, ...restProps } = this.props;
return (
<Row>
<Col md="8" id="content-block">
<SwitchTab />
</Col>
<Col md="4" id="info-block">
<InfoComponent {...restProps} />
{children}
</Col>
</Row>
);
}
}
// Usage
<Wrapper>
<OtherComponent />
</Wrapper>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With