React Fragments

The final thing we're going to talk about in this chapter is the new support for React Fragments! React Fragments are a brand-new, but important, feature. Previously, if you wanted to include multiple components at the same level, you always had to have a root component, even for things such as multiple table rows, which never really made sense; you'd have to nest <td> tags inside of <div>, which is just weird.

It ends up with you having to choose between writing what's technically invalid HTML or writing compliant React code, which tends to just end up as awkward or bad code to get around the limitation. Now, instead, we can write code encased in special Fragment tags (<Fragment> and </Fragment>) to denote the start and end of a fragment, respectively. We can reference these as <React.Fragment>, <Fragment> (if we choose to import Fragment where we import Component, such as in the following line of code), or as <> for a shortcut:

import React, { Fragment, Component } from "react";
A quick warning about using the shortcut syntax of <> and </>: if you're using Fragments inside of code that's building a list of Fragments, you can't use the shortcut syntax and still specify a key property; you will have to use either React.Fragment or Fragment.

If we go back to src/TodoList.js, in our renderItems() function, we can see the perfect place to replace an extraneous <div> with a Fragment instead:

 renderItems() {
return this.state.items.map(description => (
<Fragment key={"item-" + description}>
<Todo
key={description}
description={description}
removeTodo={this.removeTodo}
/>
<Divider key={"divide-" + description} />
</Fragment>
));
}

At the top of the function, where we import Component as a named import from React, we'll also need to include Fragment, similar to the line of code a little bit higher up in this section.

The end result is otherwise identical; the major difference is that instead of placing each of the Todos and Dividers inside of extra div for no reason, they can all sit next to each other in the DOM tree and keep your code significantly cleaner, especially in the case of working with HTML tables, where introducing an extra div will actually just break your code!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.173.112