Home > database >  react router does not render when the url changes
react router does not render when the url changes

Time:12-28

I have the following in Main component;

<Routes>
    <Route path="/forum/*" element={<Forum />} />
</Routes>

and this inside Forum component

<Routes>
    <Route path=":topicName" element={<QuestionFeed />} />
</Routes>

When I first navigate to /forum/programming, the router renders as expected. But after clicking on a Link only the URL updates and the component does not re-render.

<Link to="programming">

Why does the router not render when clicking on a Link but renders if I visit the url manually. ?

"react":            "^17.0.2",
"react-dom":        "^17.0.2",
"react-router-dom": "^6.2.1",

CodePudding user response:

Inside the Forum component you will have to specify the parent route url also. You can get the parent url from the match props inside the Forum component, then you can do

<Routes>
  <Route path={`${parentRoute.url}/:topicName`} element={<QuestionFeed />} />
</Routes>

Or in your case this should also work

<Routes>
  <Route path="/forum/:topicName" element={<QuestionFeed />} />
</Routes>

Basically you have to specify the full path for path in Route

Then you can use the link component like <Link to="/forum/programming"> and it should work

CodePudding user response:

Solved

The problem was in QuestionFeed component. The state was only being updated in useEffect that only executed once since the dependency array was empty. Added the url parameter to the list to have it update the state.

    const { topicName } = useParams();

    useEffect(() => {
        ...
        setQuestions(questions || []);
        ...
        .catch(error => console.log(error));
    }, []); // empty dependency array
    const { topicName } = useParams();

    useEffect(() => {
        ...
        setQuestions(questions || []);
        ...
    }, [topicName]);

CodePudding user response:

You need to try with full url /forums/programming.

  • Related