In React, when writing JSX, there is a limitation: you can only return one parent item. You cannot have multiple elements directly under the return statement. However, there are several solutions to overcome this limitation.
Solution 1: Wrap Components and Elements in a <div>
One common way to solve this issue is by wrapping the components and other HTML elements in a <div>
:
const Pets = () => {
return (
<div>
<Dog />
<Cat />
</div>
);
};
However, this approach introduces an additional HTML element which may not be necessary in the final rendered HTML.
Solution 2: Return an Array of JSX Elements
Another solution is to return an array of JSX elements:
const Pets = () => {
return [
<Dog />,
<Cat />
];
};
This approach allows you to return multiple JSX elements without the need for a wrapping <div>
. However, keep in mind that you need to add a unique key to each element in the array to avoid the warning about missing keys.
Solution 3: Use Fragments
Fragments are a relatively new feature in React that solves this problem for us. Fragments let you group a list of children without using an additional wrapping element:
const Pets = () => {
return (
<React.Fragment>
<Dog />
<Cat />
</React.Fragment>
);
};
Fragments work similarly to the <div>
element we added before, but they do not appear in the resulting HTML rendered to the browser. It’s a clean and concise solution.
In conclusion, when faced with the need to return multiple elements in JSX, you can use either a wrapping <div>
, an array of JSX elements, or the <React.Fragment>
syntax. Choose the solution that best fits your use case and helps you maintain a clean and readable code structure.