history.push react code example

Example 1: react router dom push

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <Button type="button" onClick={handleClick}>
      Go home
    </Button>
  );
}

Example 2: this.props.history.location.push

props.history.push({  pathname: '/register', state: data_you_need_to_pass});

Example 3: use history in react router

import {createBrowserHistory} from 'history';import {useRouterHistory, Router, Route} from 'react-router';const history = useRouterHistory(createBrowserHistory)({  basename: '/basename'});history.listen(location => {  history.push('/super/url');});const router = (  <Router history={history}>    <Route path=/' component={App}></Route>  </Router>);

Example 4: history.push

// usually all you need
<Link to="/somewhere"/>

// but you can use a location instead
const location = {
  pathname: '/somewhere',
  state: { fromDashboard: true }
}

<Link to={location}/>
<Redirect to={location}/>
history.push(location)
history.replace(location)

Example 5: history.pushstate

history.pushState(state, title[, url])

Example 6: props history

class Comp extends React.Component {
  componentDidUpdate(prevProps) {
    // will be true
    const locationChanged =
      this.props.location !== prevProps.location;

    // INCORRECT, will *always* be false because history is mutable.
    const locationChanged =
      this.props.history.location !== prevProps.history.location;
  }
}

<Route component={Comp} />;