I'm trying to figure out the best ways of creating functional components that generate simple html - take this nav-links.js file for example:
export const navLinks = [
{
name: "home",
href: "/"
},
{
name: "subs",
href: "/subs"
}
];
The html my component attempts to generate just loops through each link to generate an unordered-list with list tags and a tags inside.
The problem occurs in this nav-menu.js file, where the output is just an two <ul></ul> tags with nothing inside:
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import {navLinks} from "../util/nav-links";
export const NavMenu = () => {
const lis = () => (
{navLinks}.map(link => {
return (
<li>
<Link to={link.href} key={link.href}>{link.name}</Link>
</li>
)
})
)
return (
<div id="navbar">
<ul>
{lis}
</ul>
</div>
)
}
Why is nothing rendering in the above component? I wrote some more code below that solves it, although I wonder whether it could be refactored better:
export const NavMenu = () => {
return (
<div id="navbar">
<ul>
{navLinks.map(link => {
return (
<li>
<Link to={link.href} key={link.href}>{link.name}</Link>
</li>
)
})}
</ul>
</div>
)
}
Why does the first attempt not work, and how could it be better refactored? Thanks for any help here
{lis}you use{lis()}or rename it toLis(capital letter) and try<Lis />?Array.prototype.map()onObject(since you destructured yournavLInksarray intonavLinksvariable when you didimport {navLinks} from "../util/nav-links", and then created an object{navLinks: [{name: 'home', href: '/'},{name: 'subs', href: '/subs'}]}when you wrappednavLinksinto curly braces). So your first attempt, most probably, threw an error. It would work as expected if you skipped curly braces:navLInks.map(... Though, I would prefer second approach.