Home > Mobile >  Parameter can not be passed from react route to react Component
Parameter can not be passed from react route to react Component

Time:05-26

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

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

CodePudding user response:

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

CodePudding user response:

You might wanna simplify it like this.

import React from 'react'
import {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() {

  const {id} = useParams()

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

export default ProductScreen
  • Related