Dynamic path mapping

Viewed 72

For example , my app has navigation items such as item1, item2, and so on. The items are not fixed which is coming from Content management system. I would like to call some 3rd party API on click of each item and display in the component. So, if the url for item1 is localhost:3000/content/item1.html , so if I click on this URL then I would like to call API in my corresponding single component by passing the url value:mycontent/item1.json

Navigation url can also be localhost:3000/content/item2.html or localhost:3000/content/item1/item2.html and so on. In all cases I want to route to a single component. How can I do it? I looked into online but could not find how to implement this requirement. Any example or online page?

In my express server.js I am doing this:

   <ReduxProvider store={ store }>
            <StaticRouter context={ context } location={ req.url }>
                <Layout />
            </StaticRouter>
    </ReduxProvider>

now in Layout component:

    render() {
    return (
        <div>
            <h1>{ this.state.title }</h1>
             <Navigation />
            <Switch>
                { routes.map( route => <Route key={ route.path }  { ...route } /> ) }
            </Switch>
        </div>
    );
  }

In routs.js I want to call MyComponent which matches this url pattern like this: localhost:3000/content/item2.html or localhost:3000/content/item1/item2.html and so on

export default [
{
    path: "/",
    component: Home,
    exact: true,
},
{
    path: "/content/*",  // Here I want to match pattern of the url starts with /content and call MyComponent with actual URL path
    component: MyComponent,
    exact: true,
},

 ];
1 Answers

All you need to do is to remove the exact attribute and just have path as /content and it would work

export default [
    {
        path: "/",
        component: Home,
        exact: true,
    },
    {
        path: "/content",
        component: MyComponent,
    },

];
Related