John
John

Reputation: 103

How to use <Link> react router?

I am working with reactjs and react router. I have create my router as:

ReactDOM.render(
  <Router history={browserHistory}>  
    <Route exact path="/" component={App} />
    <Route path="/:id" component={User} />
  </Router>,
  document.getElementById('root')
);

And in the App component I have a Link to the "/:id" path :

<Link to={'/'+id} >

when I am in the "/" route, my view works fine but now when I click my link, the path changes and my view changes for an instant and then gives an error in the App component (It is the component of the other route) .

I use "react-router": "^2.8.1".

PS: the error is in the setinterval function in the component {App}.

Thanks for any help in advance

Upvotes: 6

Views: 55177

Answers (3)

Vikas Yadav
Vikas Yadav

Reputation: 3356

Try to use this on the top:

import { Link } from 'react-router-dom'

refer to this: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/Link.md

Upvotes: 12

Shubham Khatri
Shubham Khatri

Reputation: 281626

The reason that you get

TypeError: Cannot set property 'innerHTML' of null

is because you are not clearing the interval when you are navigating away from the App component and since it still is running, it tries to access document.getElementId("demo") which is no longer there

what you need to do is clear the timer on componentWillUnmount

componentDidMount(){ 
        this.interval = setInterval(function(){ 
           document.getElementById("demo").innerHTML =moment().format('hh:mm:ss a');
        },1000);
    } 

   componentWillUnmount() {
       clearInterval(this.interval);
   }

Upvotes: 3

Adeel Imran
Adeel Imran

Reputation: 13956

Include this at the top import { IndexRoute} from 'react-router';

ReactDOM.render(
  <Router history={browserHistory}>  
   <IndexRoute path="/" component={App} />
   <Route path="/:id" component={User} />
   </Router>,
  document.getElementById('root')
);

This will distinguish your main root path with the other path.

Upvotes: 0

Related Questions