Fragments

Chindalath Traymany
2 min readDec 2, 2020

--

Photo by Dan-Cristian Pădureț on Unsplash

Learning React/Redux in three weeks was no simple task. There is a lot to follow, and it’s easy to lose track of the flow when you’re first starting out.

Amongst those who work with React, it’s common knowledge that you are only allowed to return one element in each component. If you have several elements that need to be rendered, the protocol is to wrap them in one element, such as a div. This approach especially makes it tough to read the HTML output because then, nearly everything is nested in divs.

You can see what I mean below in the HTML for my React Contact Book app.

Now that’s a lot of unnecessary clutter.

But one thing that helped me organize and read my code was using Fragments. Just compare the following code to the previous.

Not only is that much cleaner and easier on the eyes, but it’s super easy to use! Fragments are included in the React library when you import React at the top of your file.

import React from 'react'

In your return statement, all you have to do when you have multiple elements is to wrap them in <React.Fragment> ... </React.Fragment> instead of your typical div tag. Here’s an example:

const Group = (props) => {    const group = props.groups.filter(group => {        return group.name === props.match.params.name    })    return (        <React.Fragment>            <h2>{group && group.name}</h2>            <ContactsContainer group={group}/>        </React.Fragment>    )
}
export default Group

But wait… it gets even better. There is a shorthand syntax for Fragments.

Instead of typing <React.Fragment> ... </React.Fragment> every time you need to return multiple elements, you could wrap them simply in<> ... </>!

return (    <>        <h2>{group && group.name}</h2>        <ContactsContainer group={group}/>    </>)

It doesn’t get any easier than that.

The cool part? You could even use them in arrays, objects, and iterations!

return(    <>        {props.contacts && props.contacts.map(contact => (                <React.Fragment key={contact.id}>                    <h3>{contact && contact.name}</h3>                    <p>{contact && contact.phoneNumber}</p>                    <p>{contact && contact.birthday}</p>                </React.Fragment>        ))}    </>
)

Now before you implement Fragments into your React app, there are a few things worth noting. According to the React Documentation, key is currently the only attribute that can be passed into Fragments. If passing in a key, the shorthand syntax cannot be used (see above for proper use).

Happy coding!

--

--

Chindalath Traymany
Chindalath Traymany

Written by Chindalath Traymany

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

No responses yet