Home > database >  match.params.id shows white blank full screen
match.params.id shows white blank full screen

Time:04-21

I'm currently working on an e-commerce website using MERN. In ProductScreen I'm trying to show all the products details listed in Products.js. On adding match.params.id in ProductScreen.js it shows blank white page

ProductScreen.js:

import React from 'react'
import products from '../products'

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

export default ProductScreen

App.js:

import React from 'react'
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import { Container } from 'react-bootstrap'
import Header from './components/Header'
import Footer from './components/Footer'
import HomeScreen from './screens/HomeScreen'
import ProductScreen from './screens/ProductScreen'

const App = () => {
  return (
    <Router>
      <Header />
      <main className='py-3'>
        <Container>
          <Routes>
            <Route path = '/' element={<HomeScreen />} exact />
            <Route path = '/product/:id' element={<ProductScreen />}  />
          </Routes>
        </Container>
      </main>
      <Footer />
    </Router>
  )
}

export default App

Product.js:

const products = [
  {
    _id: '1',
    name: 'Airpods Wireless Bluetooth Headphones',
    image: '/images/airpods.jpg',
    description:
      'Bluetooth technology lets you connect it with compatible devices wirelessly High-quality AAC audio offers immersive listening experience Built-in microphone allows you to take calls while working',
    brand: 'Apple',
    category: 'Electronics',
    price: 89.99,
    countInStock: 10,
    rating: 4.5,
    numReviews: 12,
  }
]

export default products

Error in console log: Error in console log

CodePudding user response:

The component ProductScreen doesn't get passed any match prop. Therefore, when you try to access params.id it will throw error because it is not possible to read properties of an undefined object. This is probably why you get white screen crash.

Since ProductScreen is a functional component, you can use React Router hook instead of passing match via props. Either useRouteMatch() or useParams().

const ProductScreen = () => {
  const params = useParams() // import useParams from react-router
  const product = products.find(p => p._id === params.id)
  return (
    <div>{product.name}</div>
  )
}

BTW, when you get blank white screen, please open developer tools in browser and read the error message in console. That will help you narrow down to the exact cause of the issue.

  • Related