user8758206
user8758206

Reputation: 2191

Best way to output a very simple menu in react

I'm new to react and my question is extremely simple. I want to just know the best way to output a navigation menu on a page (i.e. literally just page links).

So my main app.js has this code:

import React, {Component} from "react";
import NavMenu from "./nav-menu";

const theLinks = [
  "home",
  "subs"
]

export default class App extends Component {
  constructor() {
    super();

    this.state = {
      navLinks: theLinks
    }
  }

  render() {
    return (
      <div id="container">
        <NavMenu navLinks={this.state.navLinks} />
      </div>
    );
  } 
}

And the nav-menu component has this code:

import React, {Component} from "react";

export default class navBar extends React.Component {
  render() {
    return (
      this.props.navLinks.map((c, i) => <a href={c[1]} key = {i} > {c[0]} </a>)
    )
  }
}

Which should (but doesn't) output is like this:

<div id="container"><a href="/index"> home </a><a href="/subs"> subs </a></div>

Why is this not outputting like the above? My gut feeling also senses that this is not a good way to output a menu or list of links. What is a better way?

Thanks for any advice here. I'm trying to learn react pragmatically and without having to study a long course.

Stackblitz: https://stackblitz.com/edit/react-hunbng?file=src%2FApp.js

Upvotes: 0

Views: 309

Answers (1)

Dom
Dom

Reputation: 734

Your array has quite a strange structure. I'd go for something more readable/usable:

App.js

import React, {Component} from "react";
import NavMenu from "./nav-menu";

const theLinks = [
  {
    name: "home",
    href: "/index"
  },
  {
    name: "subs",
    href: "/subs"
  },
]

export default class App extends Component {
  constructor() {
    super();

    this.state = {
      navLinks: theLinks
    }
  }

  render() {
    return (
      <div id="container">
        <NavMenu navLinks={this.state.navLinks} />
      </div>
    );
  } 
}

nav-menu.js

import React, {Component} from "react";

export default class navBar extends React.Component {
  render() {
    return (
      // it's considered bad practice to use the map-index as a key, hence the href as key
      this.props.navLinks.map((c) => <a href={c.href} key={c.href} > {c.name} </a>)
    )
  }
}

Upvotes: 1

Related Questions