How do I pass multiple parameters using history.push?

Viewed 857

In React I am trying to pass both pathname and another parameter using history.push. When it executes the application redirects to the specified page but the state is undefined so I cannot obtain the other parameter.

<Route path='/main' exact component={Main}  />

import { useHistory } from "react-router-dom";
var history = useHistory();
function handleSubmit(event) {
    event.preventDefault();
    history.push("/main", { state: 'test'});
};


const Main= (props) => {
    console.log(props.location.state);
};
export default Main;

In Main, props.location.state is undefined. Can you help me please?

2 Answers

You may want to try the object version of the push:

function handleSubmit(event) {
  event.preventDefault();
  history.push({
    pathname: "/main",
    state: 'test',
  });
};

Please also ensure the receiving component is also receiving route props.

const Main= (props) => {
  console.log(props.location.state);
};

If it not then ensure access to the location object via the useLocation hook or the withRouter Higher Order Component to have them injected as props.

For getting location's state in functional component without route props or withRoute HOC, you would use useLocation instead:

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

const Main= () => {
    const location = useLocation();
    console.log(location);
};

And to pass multiple variables through location state, use object:

history.push("/page1", { pathname: "test", anotherParam: "test2" });

Note that: The second param of history.push is already the state, so you don't need to name it a state

Live Example:

Edit React Router - 404 - Navbar condition (forked)

Related