Explaining React Components

Hi, I am on Components Interacting/Components Render Other Components, and I have some problem understanding the code provided:

import React from 'react';

export class NavBar extends React.Component {
  render() {
    const pages = ['home', 'blog', 'pics', 'bio', 'art', 'shop', 'about', 'contact'];
    const navLinks = pages.map(page => {
      return (
        <a href={'/' + page}>
          {page}
        </a>
      )
    });

    return <nav>{navLinks}</nav>;
  }
}

How is the part <a href={'/' + page}> supposed to work? I couldn’t see it opening up a new page.

Hi,
this App probably uses the the React Router. Can you provide a link to the lesson?

2 Likes

Are you familiar with the .map method? It iterates through an array and “maps” to another array. Here it is used to create an anchor tag for each element in the pages array. So this .map method will result in navLinks being an array of anchor elements. The part you mentioned is the opening part of the anchor tag:

        <a href={'/' + page}>
          {page}
        </a>

It creates the anchor by using string concatenation for the href. page will be the current element passed into the callback function by the map method. So for the 1st element ‘/’ + page will evaluate to ‘/home’. Then these anchor tags are all rendered inside the nav-element. Anchor tags are typically used in React to navigate to pages outside of the current app (they cause a page refresh) and React Router, like @mirja_t mentioned, is usually used to navigate between “pages” in the React App.

1 Like