ReactJS Tutorial - 25 - Fragments
Understanding React Fragments
Introduction to React Fragments
- The video begins by introducing the concept of React fragments, which allow grouping a list of children elements without adding extra nodes to the DOM.
Creating a Fragment Component
- A new file named
fragmentDemo.jsis created, and a functional component is set up using the React snippet RFC. The text "Fragment Demo" is specified in the JSX.
- The initial setup displays "Fragment Demo" in the browser. The next step involves converting a
<div>tag into an<h1>tag for better semantics.
Handling Multiple Elements in JSX
- An attempt to add multiple elements (an
<h1>and a<p>) results in an error: "JSX expressions must have one parent element."
- To resolve this, an enclosing
<div>tag is added around the elements, allowing them to be returned as one single entity.
Issues with Extra DOM Nodes
- While this resolves the error, it introduces an unnecessary extra
<div>node in the DOM tree between components.
- This is where React fragments become useful; replacing the enclosing
<div>withReact.Fragmenteliminates additional nodes from being rendered.
Practical Example with Tables
- A more complex example involves creating two new files:
table.jsandcolumns.js. Intable.js, a table structure is established using appropriate tags like<tbody>and<tr>.
- In
columns.js, two columns are defined within a functional component. However, returning multiple elements requires wrapping them in a parent element.
Resolving Nesting Warnings
- Including these columns leads to warnings about invalid nesting (e.g., having
<td>inside a<div>).
- By replacing this wrapping
<div>withReact.Fragment, all console warnings disappear, ensuring valid HTML structure without unnecessary nodes.
Key Attributes for Lists
- Itβs noted that React fragments can accept key attributes when rendering lists of items. For instance, mapping over an array allows specifying keys directly on fragments.
Shorthand Syntax for Fragments
- A shorthand syntax for fragments exists using empty opening and closing tags (
<> </>), which does not create actual DOM elements but has limitations regarding passing key attributes.
Conclusion on Usage of Fragments