Skip to content

Latest commit

 

History

History
61 lines (49 loc) · 1.98 KB

05-react-render-two-elements-side-by-side-with-react-fragments.md

File metadata and controls

61 lines (49 loc) · 1.98 KB

05. Render two elements side-by-side with React Fragments

Notes

  • In React, you can’t render two React elements side-by-side (<span>Hello</span><span>World</span>). They have to be wrapped in another element (like a <div>).
  • This may seem like an odd limitation, but when you think about the fact that JSX is compiled to React.createElement calls, it makes sense.
  • React Fragments let you group a list of children without adding extra nodes to the DOM.
  • Using the React Fragments API:
<body>
  <div id="root"></div>
  <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
  <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
  <script type="text/babel">
    const helloElement = React.createElement('span', null, 'Hello');
    const worldElement = React.createElement('span', null, 'World');
    // Using the React Fragments API:
    const element = React.createElement(
        React.Fragment,
        null,
        helloElement
        worldElement
    )
    ReactDOM.render(element, document.getElementById('root'));
  </script>
</body>
  • You can also use a React Fragments Element:
const element = (
  <React.Fragment>
    <span>Hello</span>
    <span>World</span>
  </React.Fragment>
);
  • Since React Fragments is so common, JSX has a special syntax for it:
const element = (
  // open and closing angle brackets
  <>
    <span>Hello</span>
    <span>World</span>
  </>
);

Additional resource