Search code examples
reactjsreactstrapreact-icons

Add react icon(s) dynamically to navbar item(s) in component


Bear with me, I'm learning React so I'm a beginner. I'm trying to create a bottom navigation panel. Rather than hardcoding each navbar element, I have found good examples of storing navbar elements in an array then mapping that onto your navbar. I have gotten the below to work, except I'm not sure how to dynamically reference the icon in my navTabs array within the component itself? I can add (for example) <FaIdCard /> without issue, but I don't want to have to hard code this as it would defeat the point of generating the navigation from the array.

import React from 'react';
import { Nav, NavItem} from 'reactstrap';
import { NavLink } from 'react-router-dom';
import { FaIdCard, FaInfoCircle } from "react-icons/fa";


/* This array will be mapped onto our nav elements */
const navTabs = [{
    route: "/about",
    icon: FaInfoCircle,
    label: "About"
},{
    route: "/customer",
    icon: FaIdCard,
    label: "Customer"      
}]

const Navigation = (props) => {
    return (
        <div>
            <nav className="navbar fixed-bottom navbar-light" role="navigation">
                <Nav className="w-100">
                    <div className="d-flex flex-row justify-content-around w-100">
                        { 
                        /*  index is a built-in part of .map that gives u index number. 
                            The grave accent (`) is used for template literals, or combining variables, javascript and text/html
                        */
                            navTabs.map((tab, index) =>(
                                <NavItem key={`tab-${index}`}> 
                                    <NavLink to={tab.route} className="nav-link" activeClassName="active">
                                        <div className="row d-flex flex-column justify-content-center align-items-center">
                                            <div>{tab.label}</div>
                                        </div>
                                    </NavLink>
                                </NavItem>
                            ))
                        }
                    </div>
                </Nav>
            </nav>
        </div>
    )
  };
  
  export default Navigation;

Solution

  • Try to use the icon components for your icon property:

    const navTabs = [{
        route: "/about",
        icon: <FaInfoCircle />,
        label: "About"
    },{
        route: "/customer",
        icon: <FaIdCard />,
        label: "Customer"      
    }]
    

    Then add it to the NavItem like this:

    <NavItem key={`tab-${index}`}>
      <NavLink to={tab.route} className='nav-link' activeClassName='active'>
        <div className='row d-flex flex-column justify-content-center align-items-center'>
          <div>
            {tab.icon} {tab.label}
          </div>
        </div>
      </NavLink>
    </NavItem>;