Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parameter can not be passed from react route to react Component

I have tried the previous solutions but it seems that the v6 of react-dom is not working that way.

I can not pass the id from the path to the component.

app.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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';
import ProductScreen from './screens/ProductScreen';

function App() {
  return (
    <Router>
      <Header/>
      <main className='py-3'>
        <Container >
         <Routes>
           <Route path="/" exact element={<HomeScreen/>} />
           
            {/* Please check this. I am passing id as a param */}
           <Route path="/product/:id"  element={<ProductScreen/>} />
         </Routes>
        </Container>
      </main>
      <Footer/>
    </Router>
  );
}

export default App;

The problem is in

<Route path="/product/:id"  element={<ProductScreen/>} />

I am passing the :id to the ProductScreen component.

ProductScreen.js

import React from 'react'
import {Link} from 'react-router-dom'
import {Row, Col, Image, ListGroup, Button, Card} from 'react-bootstrap'
import Rating from '../components/Rating'
import products from '../products'

function ProductScreen({match}) {
  const product = products.find((p)=>p._id==match.params.id)
  return (
    <div>
      {product.name}
    </div>
  )
}

export default ProductScreen

I can not access the product id from the path.

error:
enter image description here

>Solution :

You need to get the useParams hook in order to use params.
https://reactrouter.com/docs/en/v6/getting-started/tutorial#reading-url-params

You can do it like this:

import React from 'react'
import {Link, useParams} from 'react-router-dom'
import {Row, Col, Image, ListGroup, Button, Card} from 'react-bootstrap'
import Rating from '../components/Rating'
import products from '../products'

function ProductScreen({match}) {
  const params = useParams()
  const product = products.find((p)=>p._id==params.id)
  return (
    <div>
      {product.name}
    </div>
  )
}

export default ProductScreen
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading