Display navbar item with Map() in React

Display navbar item with Map() in React

·

1 min read

1. Create Items in your navbar.js file

import React from 'react';

const navItems = [
    {
        name: 'Home',
        href: '#home'
    },
    {
        name: 'About',
        href: '#about'
    },
    {
        name: 'Contact',
        href: '#contact'
    }
    ,
    {
        name: 'Hi',
        href: '#contact'
    }
]

2. I am using the function component

const Navbar = () => {
    return (    
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
               <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
                      {
                          navItems.map(navItem => {
                                 return <li class="nav-item">
                                                <a class="nav-link" href={navItem.href}>{navItem.name}           
                                                </a>
                                      </li>
                       })
                          }
               </ul>
         </div> 
    );
};

export default Navbar;
  1. mapping navItems and the map will keep all data in navItem
  2. Then I can call it where I need <a class="nav-link" href={navItem.href}> {navItem.name} </a>
  3. For example I need nameso that I declare navItem.name