React ~ Router ~ Passing Props to Link - rohit120582sharma/Documentation GitHub Wiki

When building an app with React Router, sometimes you’ll need to pass data from the Link component to the new route. There are two different ways to do it. The first is through URL Parameters and the second is through state.

URL parameters are great, but they’re not meant to serve as a way to get data from one route to another as they’re limited to just strings. What if instead of just a string, we wanted to pass along something a little more complex, like an object or an array? There would be no way to do that with URL parameters. This brings us to the second way to pass data from one route to another and that’s with state.



React Router (v4)

Anytime you pass data along via the state property, that data will be available in the component as a property on props.location.state.

<Link to={{
    pathname: '/tylermcginnis',
    state: {
        fromNotifications: true
    },
    search: {
        filter: 'top',
        origin: 'im'
    }
}}>Tyler McGinnis</Link>

// Profile.js
class Profile extends React.Component {
    componentDidMount() {
        const { handle } = this.props.match.params;
        const { fromNotifications } = this.props.location.state;

        console.log(this.props.location.search); // ?filter=top&origin=im
    }
    render() {
        return null;
    }
}


React Router (v5)

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

<Link to={{
    pathname: '/tylermcginnis',
    state: {
        fromNotifications: true
    },
    search: {
        filter: 'top',
        origin: 'im'
    }
}}>Tyler McGinnis</Link>

function Profile() {
    const handler = useParams();
    const location = useLocation();
    const { state, search } = location;

    return (
        ...
    );
}
⚠️ **GitHub.com Fallback** ⚠️