sably
sably

Reputation: 177

What are the differences between using the Link component in react-router and calling `window.history.pushState()` manually?

in my code when i click button, component Aaaaa is not re-rendered, but when i tap on link, component Aaaaa is re-rendered. i can't find cause of it?

function App() {
  return (
    <>
        <button onClick={() => window.history.pushState('','','/about')}>About</button>
        <Link to='/about'>to About</Link>
        <Aaaaaa/>
    </>
  );
}

and:

Aaaaaa(){
   const location = useLocation()
   return <div>About </div>
}

Upvotes: 4

Views: 11815

Answers (4)

Silvr
Silvr

Reputation: 31

window.history.pushState method doesn't trigger any browser event, which in turn doesn't notify react router about the update you made to the history object

React router custom Link component is most likely going to use a custom event or the observer design pattern to be able to notify and respond to changes in the window history object

Upvotes: 2

Rouan van der Ende
Rouan van der Ende

Reputation: 97

I found that window.history.pushState('','','/about') does not work as expected. The router does not update what route to display.

If you cant use a button and need to control the location programatically, but use class components wrap it in a function component like this:

... other routes

<Route exact path="/register" component={()=>{
    const history = useHistory();
    return <RegisterPage onRegister={async (account) => {
      this.setState({ account });
      history.push('/'); // sends user automatically to main page
    }} />
  }} />

...

Upvotes: 2

reza erami
reza erami

Reputation: 158

cause window.history.pushState is not using the react router so you can use link to navigate between the pages. but if you have limits and you want it to be a buttn and still navigate using react router, you can use history from react-router-dom

import { withRouter } from 'react-router-dom'
// some other codes
const { history } = props;
// some other codes
<button onClick={() => history.push('/about')}>About</button>
// some other codes
export default withRouter(MyComponent)

or you can use 'useHistory' hook if you're using react-router v5.

import { useHistory } from 'react-router-dom'
// some other codes
const history = useHistory();
// some other codes
<button onClick={() => history.push('/about')}>About</button>
// some other codes
export default MyComponent

Upvotes: 4

Shmili Breuer
Shmili Breuer

Reputation: 4147

The proper way is to use <Link to='/about'>to About</Link> when trying to navigate manually (by clicking a button) and window.history.pushState('','','/about') when trying to navigate automatically (like after completing an API call).

Upvotes: 8

Related Questions