I'm relatively new to React and I'm wondering what's the standard here.
Imagine I have a react-router like this one:
<Router history={history}>
<Route path="/" component={App}>
<Route path="home component={Home} />
<Route path="about" component={About} />
<Route path="inbox" component={Inbox} />
<Route path="contacts" component={Contacts} />
</Route>
</Router>
And now I want to remove two routes if prop.mail is set to false, so a sane way of doing that would look like this:
<Router history={history}>
<Route path="/" component={App}>
<Route path="home component={Home} />
<Route path="about" component={About} />
{ if.this.props.mail ?
<Route path="inbox" component={Inbox} />
<Route path="contacts" component={Contacts} />
: null }
</Route>
</Router>
But there are 2 routes and React returns error:
expressions must have one parent element.
I don't want to use multiple ifs here. What's the preferred React way of handling this?
Put them in an array (assign the keys also):
{ if.this.props.mail ?
[
<Route key={0} path="inbox" component={Inbox} />,
<Route key={1} path="contacts" component={Contacts} />
]
: null }
With latest React version, you can try React.Fragment also, like this:
{ if.this.props.mail ?
<React.Fragment>
<Route path="inbox" component={Inbox} />,
<Route path="contacts" component={Contacts} />
</React.Fragment>
: null }
You can leverage short hand fragments to return a list of children along with Logical '&&' Operator for conditional rendering. Nice and clean! 😄
{this.props.mail &&
<>
<Route path="inbox" component={Inbox} />,
<Route path="contacts" component={Contacts} />
</>
}
You must been use a fragment tag e.g(div, <>,...).
Check this short solution:
{ if.this.props.mail ?
<>
<Route path="inbox" component={Inbox} />
<Route path="contacts" component={Contacts} />
</>
: null }