I am working on react project. I have started using react-router-dom but the router is not working.
I want to go to homescreen but it give me 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 This is the code of homescrren.
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
It was working before when i have not added the router.
CodePudding user response:
Change element
with component
as React Router V6 works this way, and call the component when using it (<HomeScreen/>
instead of HomeScreen
). Also you would wanna use Routes
from react-router-dom
to make sure you load only one element for a given url.
Finally
homeScreen
should beHomeScreen
, otherwise it's not considered as a React component.
import Container from 'react-bootstrap/Container'
import Footer from './components/footer';
import Header from './components/header';
import './index.css';
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'
import HomeScreen from './screens/homeScreen';
function App() {
return (
<Router>
<Header/>
<main className='py-3'>
<Container >
<Routes>
<Route path="/" exact element={<HomeScreen/>} />
</Routes>
</Container>
</main>
<Footer/>
</Router>
);
}
export default App;
CodePudding user response:
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>
.