How do I pass state to IonRouterLink in Ionic 7?

88 views Asked by At

I'm using ionic 7 and react 18. I have this router link

              routerLink='/contact'
              style={{ color: 'blue', cursor: 'pointer', marginLeft: '4px' }}
            >

How would I add a state variable (prevPath) to the link such that on the component accessed by visiting the link, I can then access the state using

type ContactComponentProps = {
  contact: Contact | null
}
...
  const location = useLocation<LocationState>();
    ...
          const url = location.state?.prevPath || '/home';
1

There are 1 answers

0
VonC On BEST ANSWER

In the context of Ionic React, IonRouterLink primarily facilitates navigation using properties like href for specifying the destination URL and routerDirection for the transition animation.

If you need to pass state to a route in a React application, you would typically use the Link component from the react-router-dom package. That would allow you to pass a state via a state prop, and this state can be accessed in the target route using the useLocation hook.

import { Link } from 'react-router-dom';

// your component code

<Link to="/your-route" state={{ yourStateData }}>Link Text</Link>

And in the target component, you can access this state with:

import { useLocation } from 'react-router-dom';

// your component code

const location = useLocation();
const stateData = location.state;