React router dom v6 not populating ownProps in mapStateToProps

Viewed 325

I recently installed beta version of react-router-dom V6, because I like Outlet and object-based routes because they make my life easier. However, since I am using React-Redux, I have a problem of not being able to get URL parameters in the mapStateToProps function:

const mapStateToProps = (state, ownProps) => {
    return {
        campaign: selectCampaignById(state, ownProps.match.params.id),
    };
};

The route is defined as:

const routes = useRoutes({
        path: 'admin',
        element: <DashboardLayout />,
        children: [
            { path: '/', element: <DashboardContainer /> },
            { path: 'campaign/edit/:id', element: <CampaignEdit /> },
            { path: 'campaign/create', element: <CampaignCreate /> },
            { path: 'campaign', element: <CampaignListView /> },
            ...
        ],
    });,

In the above example, ownProps.match object is undefined, while it worked with react-router-dom V5. I want to emphasise that the routes and everything else is working, EXCEPT that I cannot get ownProps.match populated with url parameters.

Can anyone please give a solution for this. Thank you!

1 Answers

In this case you can use the equivalent useSelector() of mapStateToProps().

I don't have the complete source code of your project but I would remove the mapStateToProps declaration and inside your component you can do something like:

const { id } = useParams()

const campaign = useSelector(state => state.campaigns[id]

Don't forget to add the imports:

import { useParams } from 'react-router-dom'
import { useSelector } from 'react-redux'

More info about useSelector().

Useful answer regarding to the usage of useSelector() and mapStateToProps().

Related