Search code examples
reactjsparametersreact-router-dom

How do I pass multiple parameters using history.push?


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?


Solution

  • 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)