Home > Net >  Can' read properties of undefined (reading 'path')
Can' read properties of undefined (reading 'path')

Time:07-30

I don't understand why it gives me this error when , is this because i am using react router v6. Can someone look at this and tell if i missing something. Here is the code :

Code :

import { useParams, useMatch, Route, Routes, BrowserRouter as Router } from 'react-router-dom';

const {id} = useParams();
const [book, setBook] = useState(null);
const match = useMatch();

<Router>
            <Routes>
                <Route path={`${match.path}/`}>
                <h4>{book && book.title}</h4>
                </Route>
             
            </Routes>
        </Router>

error in console

CodePudding user response:

The useMatch hook expects a path pattern string as an argument. It's not optional. It also potentially returns null so you'd want to use a guard clause/null-check on it anyway.

If you are trying to build descendent "relative" paths then you don't need to use the old v5 patterns of using the match object's path and url values to generate nested routes and links, RRDv6 routes and links do this automatically. This assumes the Router is rendered higher up the ReactTree than the component trying to access the routing context.

Example:

import { useParams, Route, Routes } from 'react-router-dom';

...

const { id } = useParams();
const [book, setBook] = useState(null);

<Routes>
  <Route
    path="/" // <-- renders on "/" relative to the current route pathname
    element={<h4>{book && book.title}</h4>}
  />
</Routes>

For example, if the parent component to the above component is rendered on "/foobar/*" then <h4>{book && book.title}</h4> is also rendered on "/foobar". If there was a second descendent route on "/barbar" then that route's component would be rendered on path "/foobar/barbar".

  • Related