'Fragments should contain more than one child - otherwise, there‘s no need for a Fragment at all react/jsx-no-useless-fragment
I am getting this error in the app.js file in my react project:-
Fragments should contain more than one child - otherwise, there‘s no need for a Fragment at all react/jsx-no-useless-fragment
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import NavMenu from './components/NavMenu';
export default function App() {
return (
<>
<Router>
<NavMenu />
</Router>
</>
);
}
I have been trying to find a solution but couldn't get one so can someone pls tell me how to fix this
Any help would be appreciated
Solution 1:[1]
Your component is returning the equivalent to this:
<React.Fragment>
<Router>
<NavMenu />
</Router>
</React.Fragment>
<></> is shorthand syntax.
The fragment is for cases when you want to return more than one component or element as siblings. But because a component must only return one thing, we can use fragments to put a sort of "invisible wrapper" around two components to make it appear to be one.
Here is an example of when a component might like to use a fragment:
return (
<>
<Navbar />
<Router>
<Routes>
<Route index element={<Home />} />
</Routes>
</Router>
</>
);
Because you are only returning one element inside that fragment, it is not really doing anything, so just remove the fragment or include another component inside of it.
Solution 2:[2]
I got the same error today due to the fact that I had ternary operator in the following manner:
<>
{isCheck ? (
<button
....
>
</button>
) : (
<div className={class}>
....
</div>
)}
</>
Whan I realized is that without the wrapping element it was not running as it is supposed to be.
My solution was just to replace the Fragment with div.
That made lint happy and the red flag disappeared.
Solution 3:[3]
React is not supposed to return adjacent elements, so if you just return one component or element there is no need for using <></>.
Remove <> </> as it might hinder your program for now
But in future for more than 1 components you might need to use these.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | CyberMessiah |
| Solution 3 |
