CodeFingers
CodeFingers

Reputation: 43

Get an id from a path in a specific route

I'm not able to get "id" in "match" if I have a route like this

<PrivateRoute path="/mypage/:id" Component={TestPage} currentUser={user} />

My private route is

const PrivateRoute = ({ path, Component, myParameter }) => {
    const { isAuthenticated } = useContext(AuthContext);

    return isAuthenticated ? (
        <Route path={path} render={() => <Component myParameter={myParameter} />} />
    ) : (
            <Redirect to="/login" />
        );
};

Before I was able to get id using match, before I made changes recommended for me in this post

Thanks

Upvotes: 2

Views: 81

Answers (1)

Soufiane Boutahlil
Soufiane Boutahlil

Reputation: 2604

This is an alternative way to pass props to your page, if you are using render in your route:

const PrivateRoute = ({ path, Component, myParameter }) => {
    const { isAuthenticated } = useContext(AuthContext);

    return isAuthenticated ? (
        <Route path={path} render={(props) => <Component myParameter={myParameter} {..props} />} />
    ) : (
            <Redirect to="/login" />
        );
};

On your page component, you can access your param by using props:

const { id } = props.match.params

Upvotes: 1

Related Questions