[React.JS] <> Fragments? </>

Yura Choi
2 min readNov 29, 2017

--

The newest version of React, React v.16.2.0, has been launched this week. The most prominent feature of this version is Fragments. For those of you who have been working on projects using React, you may be familiar with wrapping your child components using <div> or <span> in your render():

render(){
return(
<div>
<Navbar/>
<h2> Heading </h2>
</div>
);
}

If you don’t wrap your child components using those tags, then you’d face a syntax error message reminding you that adjacent JSX elements must be wrapped in an enclosing tag. Essentially, you can’t return more than once at a time in a method call, and you can’t return nothing either, so using <div> or <span> tags has been necessary when working with React.

At the end of the day, however, we’re all trying to avoid expensive DOM operations and make our code as efficient as possible. With this updated version of React, you can return your child components without adding extra nodes to the DOM using Fragments.

Fragment is a first-class component that you can use to wrap your child components and elements in place of <div> or <span> tags:

render(){
return(
<Fragment>
<Navbar/>
<h2> Heading </h2>
</Fragment>
);
}

or

render(){
return(
<React.Fragment>
<Navbar/>
<h2> Heading </h2>
</React.Fragment>
);
}

If your child in an array or iterator asks for key props, you can use that attribute, and only that attribute, by passing it directly to <Fragment /> :

render(){
return(
<dl>
{props.list.map(item =>(
<Fragment key={item.id}>
<dt>{item.name}</dt>
<dd>{item.description}</dd>
</Fragment>
)
)}
</dl>
);
}

If you don’t need to pass any attributes / keys, you can also use empty tags <></> to indicate a fragment:

render(){
return(
<>
<Navbar/>
<h2> Heading </h2>
</>
);
}

Ready for this update / want to find out more about other supporting ingredients? Visit here!

--

--