nusantara
nusantara

Reputation: 1266

How to pass string into react-router-dom Route as function?

I'm using React 16.11.0 and react-router-dom 5.1.2.

I have an array of objects representing pages like this:

const pages = [{ url: "/", component: "Home" }, {...}, ... ]

Update: Maybe I should mention this is from a JSON string so I don't get to determine the type of the values.

I want to dynamically generate Routes in React by mapping over it:

import Home from './components/Home';
...
<BrowserRouter>
    <div className="App">
      <Switch>
        {pages.map(page => (
            <Route path={page.url} component={page.component} />
        ))}
      </Switch>
    </div>
</BrowserRouter>

page.url works but URLs can be strings anyway. page.component is not loading properly, I think because it is a string whereas the imported Home is a React function component.

I've tried to use eval() and Function() to convert the page.component string into objects but they don't work.

I've tried the docs and search engines but haven't been able to figure out a solution. Maybe I'm searching in the wrong places.

Is this possible? How should I go about doing it?

Upvotes: 0

Views: 1443

Answers (3)

kind user
kind user

Reputation: 41893

Actually you can even avoid importing modules - require comes handy:

const pages = [{ url: "/", component: "Home" }, {...}, ...]
   .map((obj) => (
      { url: obj.url, component: require(`./components/${obj.component}`).default }
   );

And then following your logic:

<Switch>
   {pages.map(page => (
      <Route path={page.url} component={page.component} />
   ))}
</Switch>

Upvotes: 2

Y M
Y M

Reputation: 2202

For the solution the only part you need is to create components dynamically, so

const pages = [
   { url: "/", component: Home },
   { url: "/about", component: About }
 ];

Keep in mind components should be defined before such as Home, About etc.

Upvotes: 0

milktae
milktae

Reputation: 31

Try setting page.component to Home.

Instead of this:

const pages = [{ url: "/", component: "Home" }, {...}, ... ]

Try this:

const pages = [{ url: "/", component: Home }, {...}, ... ]

Upvotes: 0

Related Questions