Search code examples
javascriptreactjsreact-routerreact-props

How to pass props with history.push


I have 2 pages: betslip.jsx and receipt.jsx.

When a button is clicked in betslip.jsx I redirect the user to receipts.jsx, giving value for 2 props with the following code:

history.push({
    state: { authorized:true, total:10},
    pathname: '/receipt'
})
        

From my reading, this SHOULD work but the prop values are never received in receipts as receipts look like this:

export default function Receipt({authorized, total}) {

    console.log('authorized: ', authorized);
    console.log('total: ', total);

    if(!authorized){
        return <Redirect to="/" />;
    }
    return (
        <div>
            <h1>hello</h1>
        </div>
    )
}

Authorized is still false, the total is still 0 (their initial values).

Am I missing something obvious here? Pls advice


Solution

  • The answer is to do this inside of the page you want to direct to:

    const location = useLocation();
    if(location.state){
        authorized = location.state.authorized;
        total = location.state.total;
    } else{
        if(!authorized){
            return <Redirect to="/" />;
        }
    }