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

Can' read properties of undefined (reading 'path')

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

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

>Solution :

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".

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