1. Where does it come from?
React Fragments were introduced in React version 16 as a feature to solve specific rendering issues.
- Origin: Before this, React components had to return a single root element. This limitation hindered certain layout implementations and could lead to unnecessary DOM elements.
-
Comparison: Before the introduction of Fragments, developers often used
extra
<div>
or other elements to wrap component content, even when these elements were not always necessary in the DOM.
2. What is it?
React Fragments allow components to return multiple elements without the need for an additional DOM element to wrap them.
- Method of Solution: Fragments act like an invisible container that can hold multiple child elements but do not produce extra markup in the DOM structure.
-
Three Key Principles:
- Use Fragments when you need to return multiple elements without adding extra DOM nodes.
-
Declare Fragments using
<React.Fragment>
or its shorthand form<>
. - Fragments are particularly useful in components like tables and lists that require specific structures.
Example:
- Background
-
Suppose you need to return multiple
<li>
elements in a component, but do not want them wrapped in an additional<div>
or other elements. - Application
- Use Fragments to directly return these
<li>
elements. - Code Example
-
function ListItem() { return ( <React.Fragment> <li>Item 1</li> <li>Item 2</li> </React.Fragment> ); }
3. Where is it going?
- Limitations: Fragments are invisible and cannot be used as containers with accessible attributes, nor can they receive styles.
- Direction for Optimization: Continue exploring different component design patterns to optimize component structure and reduce unnecessary DOM nodes.
- Future Development: As the React ecosystem continues to evolve, the use of Fragments might become more widespread, helping developers to handle components and DOM structures more flexibly.