1.

Explain Fragments in React 16?

Answer»

React Fragments is a much-needed feature introduced in  React 16.2 that helps US to get rid of wrapper div, used inside components.

We will consider the below React code. Here we have a code for a simple TODO, which has an adjacent “h2” and a “ol” TAG.

render() {    return (        <h2>Todos:</h2>        <ol>        {this.state.items.map(item => (          <li key={item.id}>            <label>              <input type="checkbox" checked={item.done} />              <span className={item.done ? "done" : ""}>{item.text}</span>            </label>          </li>        ))}        </ol>    )  } }

If we run the above code like this only, we will get the most common React error.

SyntaxError: Inline Babel script: Adjacent JSX elements must be wrapped in an enclosing tag (21:8)   19 | return (   20 | <h2>Todos:</h2> > 21 | <ol> | ^ 22 | {this.state.items.map(item => (   23 | <li key={item.id}> 24 | <label>

To FIX this error, we will wrap everything inside a <div> tag.

render() {    return (    <div>        <h2>Todos:</h2>        <ol>        {this.state.items.map(item => (          <li key={item.id}>            <label>              <input type="checkbox" checked={item.done} />              <span className={item.done ? "done" : ""}>{item.text}</span>            </label>          </li>        ))}        </ol>      </div>      )  }

Now, the unnecessary “div” creates a lot of problems. Suppose, we are using Flexbox in our parent component and this was a Child Component and the <h2> and <ol> were flex children. Now we introduce this <div> since in Flexbox it will be considered as a flex item, this will break our CSS style.

Now, we can use Fragments instead of <div> to get rid of the additional problem it caused. Fragment doesn’t have any special meaning to browser, so the problem of Flexbox item is solved.

render() {    return (    <React.Fragment>        <h2>Todos:</h2>        <ol>        {this.state.items.map(item => (          <li key={item.id}>            <label>              <input type="checkbox" checked={item.done} />              <span className={item.done ? "done" : ""}>{item.text}</span>            </label>          </li>        ))}        </ol>      </React.Fragment>      )  }

We can also get rid of  React.Fragment, if we import Fragment in the import statement.

import React, { Component, Fragment } from 'react'; ... render() {    return (    <Fragment>        <h2>Todos:</h2>        <ol>        {this.state.items.map(item => (          <li key={item.id}>            <label>              <input type="checkbox" checked={item.done} />              <span className={item.done ? "done" : ""}>{item.text}</span>            </label>          </li>        ))}        </ol>      </Fragment>      )  }


Discussion

No Comment Found