I am working on a React project, everything working fine. Then I have started using react-router-dom
but the router is not working. I want to go to homescreen but it give me these errors instead:
app.js:
import Container from 'react-bootstrap/Container'
import Footer from './components/footer';
import Header from './components/header';
import './index.css';
import {BrowserRouter as Router, Route} from 'react-router-dom'
import HomeScreen from './screens/homeScreen';
function App() {
return (
<Router>
<Header/>
<main className='py-3'>
<Container >
<Route path="/" exact component={HomeScreen} />
</Container>
</main>
<Footer/>
</Router>
);
}
export default App;
HomeScreen.js:
import React from 'react'
import products from '../products'
import {Row, Col} from 'react-bootstrap'
import Product from '../components/product'
function homeScreen() {
return (
<div>
<h1>Latest Products</h1>
<Row>
{products.map(product =>(
<Col key={product._id} sm={12} md={6} lg={4} xl={3}>
<Product product={product} />
</Col>
))}
</Row>
</div>
)
}
export default homeScreen
Juan Pablo Isaza
Make sure that your Node version is not higher than 16.15.0
, the current stable version. If it's the case, downgrade it. For that you could use n package from npm
. Delete node_modules
, package-lock.json
or yarn.lock
if you are using yarn
and start over:
# if one of the commands does not pass, you may need to precede them with sudo
npm i -g n
n stable
rm -rf node_modules package-lock.json yarn.lock && npm install
Make sure all your components starts with a capital letter, homeScreen
should be HomeScreen
. Change component
property of Route
to element
as React Router Dom v6
works this way, and call the component when using it. Also you would wanna wrap your Route
components inside a Routes
to make sure you load only one element for a given url:
<Routes>
<Route path="/" exact element={<HomeScreen/>} />
</Routes>
i suggest trying this... first, update your react-router-dom
to latest version.
then import routes like this:
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
now insert the routes component like this:
<Container>
<Routes>
<Route path="/" exact element={<HomeScreen />} />
</Routes>
</Container>
A
<Route>
is only ever to be used as the child of<Routes>
element, never rendered directly. Please wrap your<Route>
in a<Routes>
.