React ~ Router ~ URL Parameters - rohit120582sharma/Documentation GitHub Wiki

URL parameters are parameters whose values are set dynamically in a page’s URL. This allows a route to render the same component (UI) while passing that component the dynamic portion of the URL so it can change based of it.

Notice that the path has a ":" in front of it. That’s because it’s dynamic. Instead of matching literally, it’s matching for a specific pattern. With this app, anytime someone visits a route that matches that pattern (/tylermcginnis, /dan_abramov, /anything), the Profile component is going to be rendered.



React Router (v4)

Whenever React Router (v4) renders a component, it’ll pass to that component three props, match, location, and history.

A match object contains information about how a <Route path> matched the URL.

function Profile(props) {
    return (
        <div>Handle: {props.match.params.handle}</div>
    );
}

function App() {
    return (
        <div>
            <ul>
                <li><Link to='/tylermcginnis'>Tylermc Ginnis</Link></li>
                <li><Link to='/dan_abramov'>Dan Abramov</Link></li>
            </ul>
            <Route path='/:handle' component={Profile} />
        </div>
    );
}


React Router (v5)

In order to get access to the URL Parameter, you use the useParams Hook. It returns an object with a mapping between the URL Parameter and its value.

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

function Profile(props) {
    const [user, setUser] = React.useState(null);
    const { handle } = useParams();

    React.useEffect(() => {
        fetch(`https://api.twitter.com/user/${handle}`)
            .then(setUser);
    }, [handle]);

    return (
        ...
    );
}

function App() {
    return (
        <div>
            <ul>
                <li><Link to='/tylermcginnis'>Tylermc Ginnis</Link></li>
                <li><Link to='/dan_abramov'>Dan Abramov</Link></li>
            </ul>
            <Route path='/:handle'>
                <Profile />
            </Route>
        </div>
    );
}
⚠️ **GitHub.com Fallback** ⚠️