Home > front end >  ERROR : Fragments should contain more than one child - otherwise, there‘s no need for a Fragment at
ERROR : Fragments should contain more than one child - otherwise, there‘s no need for a Fragment at

Time:12-25

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

CodePudding user response:

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.

CodePudding user response:

React is not supposed to return adjacent elements, so if you just return one component or element there is no need for using <></> or <React.Fragment></React.Fragment> (these are equivalent).

You will probably encounter situations when you need to return 2 div elements one next to another (like siblings). In that case <></> will come in handy.

  • Related