Returning multiple elements in JSX

此生再无相见时 提交于 2019-12-01 17:25:26

If you are using a version below React v16 you can only return one element in jsx, so you have to wrap your elements inside one:

<div>
 <NavItem onClick={this.login}>Zaloguj się</NavItem>
 <NavItem onClick={this.login}>Zaloguj się</NavItem>
</div>

If you are using React v16 and abose you can use Fragments

import React, { Fragment } from 'react';

...
...

    <Fragment>
     <NavItem onClick={this.login}>Zaloguj się</NavItem>
     <NavItem onClick={this.login}>Zaloguj się</NavItem>
    <Fragment/>

You could also return an Array of Elements as announced here:

 return [
    <NavItem key="1" onClick={this.login}>Zaloguj się</NavItem>,
    <NavItem key="2" onClick={this.login}>Zaloguj się</NavItem>
  ];

If you are using React v16.2.0 and above you can use the shorter version of Fragments

<>
 <NavItem onClick={this.login}>Zaloguj się</NavItem>
 <NavItem onClick={this.login}>Zaloguj się</NavItem>
</>

Depending on your environment you might not be able to use all of these solutions: support for fragments

In the lastest react version you can wrap them in an empty fragment:

<>
  <NavItem onClick={this.login}>Zaloguj się</NavItem>
  <NavItem onClick={this.login}>Zaloguj się</NavItem>
</>

You need to wrap it around something, like <div> or <React.Fragment> (v16):

<React.Fragment>
  <NavItem onClick={this.login}>Log in</NavItem>
  <NavItem onClick={this.register}>Register</NavItem>
</React.Fragment>

You must use the ternary operators instead of if statements to directly render the elements in JSX.

You can use Fragment in ReactJS which is available in React 16.

which lets you group a list of children without adding extra nodes to the DOM.

You can import fragment like below ,

import React, {Fragment} from 'react';
  To render:


  <Fragment>
   <ChildA />
   <ChildB />
   <ChildC />
 </Fragment>

By using Fragment, you can avoid extra html element such div being rendered.

For more info, you can refer https://reactjs.org/docs/fragments.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!