Thursday

Fragments in React (No more unnecessary nodes in the DOM)

React.Fragment advantages:
- return elements without any extra div or any other tags
- return a list of child without having a parent node. No more wrapping elements.

Requirements:
- Babel v7.0.0-beta.31 and above
- React v16.2.0 and above

Normally you can not the following, you have to wrap it.
import React, { Component } from 'react';

class FragmentExample extends Component {
  render() {
      return (
          <li>One</li>
          <li>Two</li>
      );
    }
  }
  
export default FragmentExample;

Before react@16, you have to wrap with any tag like <ul> || <span>.
But no need anymore with Fragment.
import React, { Component, Fragment } from 'react';

class FragmentExample extends Component {
  render() {
      return (
        <Fragment>
          <li>One</li>
          <li>Two</li>
        </Fragment>
      );
    }
  }
  
export default FragmentExample;

Short syntax:
class FragmentExample extends Component {
  render() {
      return (
        <>
          <li>One</li>
          <li>Two</li>
        </>
      );
    }
  }
  
export default FragmentExample;

No comments:

Post a Comment