I'm trying to set routes in hookrouter dynamically. Current routes are an array of four objects which are mapped into li
s:
const routes = [
{ href: '/', label: 'Root' },
{ href: '/About', label: 'About' },
{ href: '/Sites', label: 'Sites' },
{ href: '/Blog', label: 'Blog' }
].map(route => {
route.key = `nav-route-${route.href}-${route.label}`;
return route;
});
// End result I need:
// export const directions = {
// '/': () => <Root />,
// '/About': () => <About />,
// '/Sites': () => <Sites />,
// '/Blog': () => <Blog />
// };
// This solution comes very close, but complains of PascalCase:
export const directions = routes.reduce(
(object, Item) =>
Object.assign(object, { [Item.href]: () => <Item.label /> }),
{});
const NavList = props => {
return (
<NavContainer>
<ul>
{routes.map(({ key, href, label }) => (
<A href={href} key={key} className='route-link'>
<li className={href === window.location.pathname ? 'active' : null}>
{label}
</li>
</A>
))}
</ul>
</NavContainer>
);
};
export default NavList;
Update: So I originally submitted this question when I was having issues putting functions into an object, but Object.assign()
inserts functions into the empty object without issue.
Now the problem I'm having is React complaining about PascalCase. Here's the exact error:
index.js:1 Warning: <About /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
But the routes array has labels with capitalized letters. I tried capitalizing 'I' in Item
for the Object.assign()
method, which interestingly React accepts the first route and errors on the second route if the I is capitalized.