Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-render same component on route params change (react-router-dom)

I have code like this:

<BrowserRouter basname="/page">
    <Switch>
         <Route path="/test/:id">
              <Page />
         </Route>
    </Switch>
</BrowserRouter>

When i switch from /page/test/1 to /page/test/2 the Page component won't re-rendering. I know the componentDidMount method won't be called but i want the Page component re-render.

How can i do that?

like image 759
Tald Avatar asked Sep 16 '25 20:09

Tald


1 Answers

Try like this if you are using React v16.8 or above

import React, { useEffect } from "react";

const Page = (props) => {
  useEffect(() => {
    //Your code comes here to fetch the data from API
 }, [props.match.params.id]);

  return (<div>Layout</div>);
}
export default Page;

For Class components

<Route path="/page/:pageid" render={(props) => (
 <Page key={props.match.params.pageid} {...props} />)
} />
like image 187
Sathishkumar Rakkiyasamy Avatar answered Sep 19 '25 12:09

Sathishkumar Rakkiyasamy