Search code examples
fluxible

How to handle dynamic route params using the fluxible-router


How can I access the dynamic navParams using the fluxible-router

For instance if I have a user component and I want to set the userId prop of the component based on the route

// configs/routes.js
module.exports = {
    home: {
        method: 'GET',
        path: '/',
        handler: require('../components/Home.jsx'),
        // Executed on route match
        action: require('../actions/loadHome')
    },
    user: {
        method: 'GET',
        path: '/user/:id',
        handler: require('../components/User.jsx')
    }
};

https://github.com/yahoo/fluxible-router/blob/master/docs/quick-start.md

How can I access that userId in the User.jsx component?


Solution

  • I assume you're using the fluxible-router here, generated apps usually do.

    Every router call includes a Payload parameter:

    module.exports = {
        user: {
            method: 'GET',
            path: '/user/:id',
            handler: require('../components/Home.jsx'),
            action: function(context, payload, done) {
                console.log( payload.toJS() );
                context.executeAction(registerCollector, payload, done);
                done();
            }
        }
    };
    

    More on where this parameter is created in the docs. But that parameter contains all your URL-parameters as a JSON object.

    To access them you have to use the payload.toJS() function though. Which took me quite a while to find, since it's not emphasised in the docs.

    To access them directly in the Component, use the handleRoute API.

    That should solve your problem.