Categories
React Answers

How to Return Multi-Line JSX in a Return Statement in React ?

Spread the love

Sometimes, we want to return multi-line JSX in another return statement.

In this article, we’ll look at how to return multi-line JSX in another return statement.

Return Multi-line JSX in a Return Statement in React

We can return multiple lines of JSX code in when we map them from an array by returning an array in the map callback.

For instance, we can write:

render() {
  return (
    {[1, 2, 3].map((n) => {
      return [
        <h3>Item {n}</h3>
        <p>{n}</p>
      ]
    }}
  );
}

We can also return a fragment to wrap around the components:

render() {
  return (
    {[1, 2, 3].map((n, index) => {
      return (
        <React.Fragment key={index}>
          <h3>Item {n}</h3>
          <p>{n}</p>
        </React.Fragment>
      )
    }}
  );
}

Conclusion

We can return multiple lines of JSX code in when we map them from an array by returning an array in the map callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *