I can't understand why it gives me the above error. I used the props way with props.match.params.languagename and it works just fine.
I did not include all imports in the code below.
import { useParams } from 'react-router';
const App = () => {
const topicsState = useSelector(state => state.topics);
const dispatch = useDispatch();
const { languagename } = useParams();
useEffect(() => {
dispatch(fetchGitHubTrendingTopics());
}, [dispatch]);
const handleRepositoryPages = () => {
const repositoryPages = topicsState.find(
topicState => topicState.name === languagename
);
if (repositoryPages)
return <RepositoryPage repositoryPages={repositoryPages} />;
};
return (
<>
<Router>
<Header topics={topicsState} />
<Switch>
<Route path="/" exact>
<Dashboard topics={topicsState} />
</Route>
<Route
path="/language/:languagename"
exact
render={handleRepositoryPages()}
/>
<Redirect to="/" />
</Switch>
</Router>
</>
);
};
The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.
react-router-dom v5 If using RRDv5 if the match prop is undefined this means that BookScreen isn't receiving the route props that are injected when a component is rendered on the Route component's component prop, or the render or children prop functions.
To get the url parameter from a current route, we can use the useParams() hook in react router v5. Consider, we have a route like this in our react app. Now, we can access the :id param value from a Users component using the useParams() hook. In React router v4, you can access it using the props.match.params.id .
You can only use useParams
in a component that is a child of your Router
component, but App
is the parent in your case.
The Router
component injects the context containing the match
into the tree below it which will be read by the useParams
hook by internally using the useContext
hook.
You can use this code , in jest test file for useParams .This worked for me
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: jest.fn().mockReturnValue({ environment: 'dev', service: 'fakeService' }),
}))
Hope this works !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With