Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - expressions must have one parent element?

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?

like image 776
Wordpressor Avatar asked Feb 20 '18 13:02

Wordpressor


People also ask

Should have a unique key prop?

When creating a list in the UI from an array with JSX, you should add a key prop to each child and to any of its' children. React uses the key prop create a relationship between the component and the DOM element. The library uses this relationship to determine whether or not the component should be re-rendered.

Why do we need React fragments?

Why do we use fragments in React? React fragments serve as a cleaner alternative to using unnecessary divs in our code. These fragments do not produce any extra elements in the DOM, which means that a fragment's child components will render without any wrapping DOM node.

What is JSX in React?

JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.

What are React fragments?

React Fragments allow you to wrap or group multiple elements without adding an extra node to the DOM. This can be useful when rendering multiple child elements/components in a single parent component.


1 Answers

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 } 
like image 163
Mayank Shukla Avatar answered Oct 04 '22 00:10

Mayank Shukla