TypeError: Cannot read property 'match' of undefined when using useParams from react-router

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>
    </>
  );
};

29 thoughts on “TypeError: Cannot read property 'match' of undefined when using useParams from react-router”

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

    Reply

Leave a Comment