Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On url change I want to re render my component how should I do that

I have two links that fetches the sample component but when I click on any one of them it gets loaded and when I click on another one it won't re-render only url gets changed. I want to re-render the component on both link clicks. Is there any way to do that??

like image 969
Sharad Pawar Avatar asked Aug 12 '16 09:08

Sharad Pawar


Video Answer


2 Answers

use location hook.

const location = useLocation();

const renderDOM = () => {
 // return your DOM, e.g. <p>hello</p>
}

useEffect(() => {
 // re render your component
 renderDOM();
},[location]);

return (
 <>
 {renderDOM()}
 </>
);
like image 120
Reza Avatar answered Sep 19 '22 07:09

Reza


I was facing similar issue sometime back when I was working on a react project.

You need to use componentWillReceiveProps function in your component.

  componentWillReceiveProps(nextProps){
     //call your api and update state with new props
  }

UPDATE

For react version 16.3+ please use componentDidUpdate

componentDidUpdate (prevProps, prevState) {
  // update state 
}

To make it more clear when your component loads for the first time by calling url www.example.com/content/a componentDidMount() is run.

Now when you click another link say www.example.com/content/b same component is called but this time prop changes and you can access this new prop under componentWillReceiveProps(nextProps) which you can use to call api and get new data.

Now you can keep a common function say initializeComponent() and call it from componentDidMount() and componentWillReceiveProps()

Your router would look something like this:-

ReactDOM.render((
     <Router history={browserHistory}>
      <Route path="/content" component={app}>
        <IndexRoute component={home}/>
        <Route path="/content/:slug" component={component_name} />
      </Route>
    </Router>
), document.getElementById('app'));

So now when you call www.example.com/content/a, a would be taken as slug. Within that component if you call www.example.com/content/b , b would be taken as slug and would be available as nextProps parameter in componentWillReceiveProps.

Hope it helps!!

like image 44
Harkirat Saluja Avatar answered Sep 21 '22 07:09

Harkirat Saluja