A
A
Alexey2021-11-10 18:38:48
Software testing
Alexey, 2021-11-10 18:38:48

The useParams hook throws undefined when testing a React component, how to fix it?

Is there a component that gets an id from a URL using the useParams hook?

import {useParams} from "react-router-dom";

function SingleVideo() {
    const {id} = useParams();


There is a route to this component: Code used for testing:
<Route path="/v/:id" component={SingleVideo} />

const history = createMemoryHistory()
    const route = `/v/${contentBackup['video-list'][0]['video_id']}`;
    history.push(route)

    render(
        <Router path={`/v/${contentBackup['video-list'][0]['video_id']}`} history={history}>
            <SingleVideo />
        </Router>,
    );


The problem is that when testing - useParams returns undefined. How to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Frontend developer, 2021-11-10
@azovl

You are passing the attribute pathto the component Router, but you need to pass this attribute to the component Route
https://v5.reactrouter.com/web/api/Route - there is an attribute on the dock path
https://v5.reactrouter.com/web/api/Router - on docker has no attribute path
also use the basic example from docker:
https://v5.reactrouter.com/web/example/basic

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question