-1

https://codesandbox.io/s/brave-surf-t3todt?file=/src/components/SidebarOption.js:187-194

The app is functioning perfectly up until I don't use the Icon component in the SidebarOption.js. As soon as I put that in there, a blank page is rendered with the console throwing up the following error

expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

SidebarOption.js

import React from "react";
import "../style/sidebarOption.css";

function SidebarOption({ text, Icon }) {
  return (
    <div className="sidebarOption">
      <h2> {text} </h2>
      {/* <Icon/> */}
    </div>
  );
}

export default SidebarOption;

Sidebar.js

import React from 'react'
import '../style/sidebar.css'
import { SidebarOption } from './'
import TwitterIcon from '@mui/icons-material/Twitter';
import HomeIcon from '@mui/icons-material/Home';
import SearchIcon from '@mui/icons-material/Search';
import NotificationsNoneIcon from '@mui/icons-material/NotificationsNone';

function Sidebar() {
  return (
    <div className="sidebar">
        <TwitterIcon />
        <SidebarOption Icon={HomeIcon} text='Home'/>
        <SidebarOption Icon={SearchIcon} text='Explore'/>
        <SidebarOption Icon={NotificationsNoneIcon} text='Notifications'/>
    </div>
  )
}

export default Sidebar;
Aayush
  • 1
  • 1

2 Answers2

1

I don't know why you're getting that error based on the code you showed here, but in the codesandbox you mentioned, the error is due to you calling the sidebar component twice with no props.

You can fix that error like this by conditional render Icon only if it's passed

function SidebarOption({ text, Icon }) {
  return (
    <div className="sidebarOption">
      <h2> {text} </h2>
      { Icon && <Icon/> }
    </div>
  );
}

export default SidebarOption;
richinrix
  • 434
  • 1
  • 3
  • 13
  • can you please explain a bit what did you mean by " calling the sidebar component twice with no props" ? – Aayush Jun 01 '22 at 11:57
  • @Aayush check line 17 and 18 in sidebar.js file in the codepen you mentioned. You mentioned SidebarOption twice with no props, if you delete those the error is not reproduced. – richinrix Jun 02 '22 at 13:52
0

What you are doing is trying to render something that is potentially undefined here: {/* <Icon/> */}. Replace this with {Icon && <Icon />} to check if the prop can be rendered.

Tea_Lover_418
  • 308
  • 2
  • 10