reactjsfrontendreact-icons

Using react-icons that are imported from another file


In a react app (created by vite), I need a list of categories to create a navigation menu. I have created this list in another file with .js extension. In the form of an array of objects:

// constants.js
import { MdHomeIcon, MdCodeIcon } from "react-icons/md";

export const categories = [
  { name: "New", icon: <MdHomeIcon /> },
  { name: "Coding", icon: <MdCodeIcon /> },
  { name: "ReactJS", icon: <MdCodeIcon /> },
];

react-icons package is installed.

My problem is this: before doing anything, react app return a syntax error in console: Uncaught SyntaxError: expected expression, got '<' in constants.js.

after solving the problem: In Sidebar.jsx, I want to map through categories to build a list with names and icons.:

// Sidebar.jsx
import { categories } from "./constants.js";

export const Sidebar = () => (
  <div>
    {categories.map((category) => (
      <div>
        <span>{category.icon}</span>
        <span>{category.name}</span>
      </div>
    ))}
  </div>
);

Solution

  • You can't include JSX inside a js file but your icons are being imported from "react-icons/md" and you use them as JSX elements.

    If you want to use these icons inside of constants.js try renaming it to constants.jsx