Atul
Atul

Reputation: 1590

React Routing Gives Error For Child Components

I am learning react and below is the very basic routing example in react

App component :

import About from './About';
import Home from './Home';
import { BrowserRouter as Router ,Routes, Route} from "react-router-dom";
import Footer from './Footer';

const App = () => 
    <Router>
        <Routes>
          
                    <Route path="/" exact element={<Home></Home>}></Route>
                    <Route path="/about" element={<About></About>}></Route>
                    <Footer></Footer>
          
        </Routes>
    </Router>


export default App

and Footer component is below -

import {Link} from 'react-router-dom'


const Footer = () => <footer>

    <nav>
        <ul>
            <li>
                <Link to="/">Home</Link>
            </li>
            <li>
                <Link to="/about">About</Link>
            </li>
        </ul>
    </nav>

</footer> 

export default Footer

The issue I am getting is , I get below error in browser -

Uncaught Error: [Footer] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

I have tried warpping all components in Routes inside Fragment like below but error is same.

Can anybody please help here , what is wrong here ?

<Router>
    <Routes>
            <Fragment>
                <Route path="/" exact element={<Home></Home>}></Route>
                <Route path="/about" element={<About></About>}></Route>
                {/* <Home></Home>
                <About></About> */}   
                <Footer></Footer>
            </Fragment>
    </Routes>
</Router>

Upvotes: 1

Views: 52

Answers (1)

Drew Reese
Drew Reese

Reputation: 202751

The error is stating that Footer isn't a Route or React.Fragment component so it shouldn't be a child of the Routes component. Just move it outside the Routes component but still inside the Router.

<Router>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
  <Footer /> // <-- outside Routes, inside Router
</Router>

Upvotes: 1

Related Questions