react how to use history.push 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 (
    
  );
}

Example 2: history.push

// usually all you need


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



history.push(location)
history.replace(location)

Example 3: history.pushstate

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

Example 4: history.push

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;
  }
}

;

Tags:

Misc Example