What is the meaning of Fragments?

Fragments are designed to address the need for a component to contain multiple elements without adding additional nodes to the DOM.

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}
Copy the code

motivation

For example, if the Columns component returns multiple TD elements, the effect will be achieved, but if we use a div parent element in the Columns component, the TD element will be invalidated. Fragments solve this problem.

class Table extends React.Component {
  render() {
    return (
      <table>
        <tr>
          <Columns />
        </tr>
      </table>); }}Copy the code
class Columns extends React.Component {
  render() {
    return (
      <div>
        <td>Hello</td>
        <td>World</td>
      </div>); }}Copy the code
<table>
  <tr>
    <div>
      <td>Hello</td>
      <td>World</td>
    </div>
  </tr>
</table>
Copy the code

usage

  • Use react. Fragment instead of div
class Columns extends React.Component {
  render() {
    return (
      <React.Fragment>
        <td>Hello</td>
        <td>World</td>
      </React.Fragment>); }}Copy the code
  • We can print the table correctly by using the above method.
<table>
  <tr>
    <td>Hello</td>
    <td>World</td>
  </tr>
</table>
Copy the code

The phrase method

  • Fragments can be declared using a syntax similar to empty tags
class Columns extends React.Component {
  render() {
    return (
      <>
        <td>Hello</td>
        <td>World</td>
      </>); }}Copy the code

Phrasal methods do not support keys or attributes.

Take the key Fragments could

  • Fragments that use declarations that display the react. Fragment syntax may have keys
function Glossary(props) {
  return (
    <dl>{props.items. Map (item => (// Without 'key' React will issue a critical warning<React.Fragment key={item.id}>
          <dt>{item.term}</dt>
          <dd>{item.description}</dd>
        </React.Fragment>
      ))}
    </dl>
  );
}
Copy the code

Key is the only property that can be passed to the Fragment.

For more, learn React!