Reputation: 105
I am trying to render React components compared to the component names in JSON file I have created. For example, I want to render the TestSection component inside the component of my Route.
This is using the routing components provided by "react-router-dom".
Here is an example of me trying to create dynamic routes and being utterly confused why this wouldn't work:
(DynamicNavigaitonSwitcher.js)
import { BrowserRouter as Route, Switch } from "react-router-dom";
navigation = [
["Explore", "/", "Explore", false],
["Profile", "/profile/", "TestSection", false],
["Messages", "/messages/", "TestSection", false],
["Listings", "/listings/", "TestSection", false],
["Settings", "/settings/","TestSection", false],
["Login", "/login/","TestSection", false],
["Sign-up", "/signup/", "TestSection", false]
]
const Explore = () => {
return (
<div>
<h1>Explore !!</h1>
</div>
)
}
const TestSection = () => {
return (
<p>Hey</p>
)
}
const Components = {
testsection: TestSection,
explore: Explore
};
const DynamicRoutes = navigation.map((navItem) => {
return (
<Route path={navItem[1]} key={navItem[0]} name={navItem[0]} component={Components[navItem[2]]}/>
)
}
);
const DynamicNavigationSwitcher = () => {
return (
<div>
<Switch>
{DynamicRoutes}
</Switch>
</div>
)
}
export default DynamicNavigationSwitcher;
Upvotes: 0
Views: 1619
Reputation: 945
There are some syntax errors:
Test this code, I correct the previous errors and its worked for me:
import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
const navigation = [
["Explore", "/", "explore", false],
["Profile", "/profile/", "testsection", false],
["Messages", "/messages/", "testsection", false],
["Listings", "/listings/", "testsection", false],
["Settings", "/settings/", "testsection", false],
["Login", "/login/", "testsection", false],
["Sign-up", "/signup/", "testsection", false]
];
const Explore = () => {
return (
<div>
<h1>Explore !!</h1>
</div>
);
};
const TestSection = () => {
return <p>Hey</p>;
};
const Components = {
testsection: TestSection,
explore: Explore
};
const DynamicRoutes = () => {
return navigation.map(navItem => {
return (
<Route
path={navItem[1]}
key={navItem[0]}
name={navItem[0]}
component={Components[navItem[2]]}
/>
);
});
};
const DynamicNavigationSwitcher = () => {
return (
<BrowserRouter>
<Switch>
<DynamicRoutes />
</Switch>
</BrowserRouter>
);
};
export default DynamicNavigationSwitcher;
Upvotes: 1