1. 程式人生 > >[React] Return a list of elements from a functional component in React

[React] Return a list of elements from a functional component in React

We sometimes just want to return a couple of elements next to one another from a React functional component, without adding a wrapper component which only purpose would be to wrap elements that we want to render.

In this one minute lesson we are going to learn how to solve this problem by returning an array of components and as such - avoid adding unnecessary div

 wrappers.

 

Way 1:

import React from "react";
import "./App.css";

const App = () => {
  return (
    <>
      <div className="box">One</div>,
      <div className="box">Two</div>,
      <div className="box">Three</div>
    </>
  );
};

export 
default App;

 

Way 2:

import React from "react";
import "./App.css";

const App = () => {
  return [
    <div className="box">One</div>,
    <div className="box">Two</div>,
    <div className="box">Three</div>
  ];
};

export default App;