Categories
React Answers

How to return multiple lines JSX in another return statement in React?

Spread the love

Sometimes, we want to return multiple lines JSX in another return statement in React.

In this article, we’ll look at how to return multiple lines JSX in another return statement in React.

How to return multiple lines JSX in another return statement in React?

To return multiple lines JSX in another return statement in React, we can wrap our components with fragments.

For instance, we write

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

to wrap the h3 and p elements in the React.Fragement component in the map callback.

Then these elements will be rendered without a wrapper element around them.

Conclusion

To return multiple lines JSX in another return statement in React, we can wrap our components with fragments.

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 *