Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you map a a list of routes for React?

So, I want to create a list of items, just as one would map a bunch of li elements into a given ul, but instead, to do the same with routes, however, how can I represent the name of the route element component into the element property, i.e. how could I represent this:

const navTitlesArray = ["routeComponent1", "routeComponent2", "routeComponent3",...]

const navRoutes = navTitlesArray.map( routeTitle => <Route key={`${routeTitle}`} path={`/${routeTitle}`} element={<{routeTitle}/>}></Route>)

Specifically pointing towards the element property, assuming that my array holds the strings of the same titles as my route components, but right now it will not work as the routeTitle = string

CURRENTLY, as a solution, I did find the option to create a second array, with my components (given that I have imported them…) and use a loop to give the element prop a value from the 2nd array ( the array of the components), as such:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const navTitlesArray = ["routeComponent1", "routeComponent2", "routeComponent3", ...]
const navComponentsArray = [<RouteComponent1 />, <RouteComponent2 />, <RouteComponent3 />, ...]

for(let i = 0; i < navTitlesArray.length; i++){
        let route = <Route key={`${navTitlesArray[i]}`} path={`/${navTitlesArray[i]}`} element={navComponentsArray[i]}></Route>
        navRoutes.push(route)

This DOES work, but I feel like if there is an option to implement the code as shown first, it would be a lot more efficient

>Solution :

replace your string array with jsx elements objects

const navTitlesArray = [{path: 'routeComponent1' , component: <routeComponent1/>},...]

const navRoutes = navTitlesArray.map( routeTitle => <Route key={`${routeTitle.path}`} path={`/${routeTitle.path}`} element={routeTitle.component}></Route>)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading