Corrent way to pass material icons as props

Hello. I’m trying to create Sidebar component and inside of it render SidebarOptions which are distinct buttons of a sidebar. The problem appears when I’m trying to pass Material UI icons (HomeIcon, SearchIcon etc) as props to my child component. The error says: ‘Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object’. So how can I fix it and pass icon as prop?

//Sidebar component
import React from 'react';

import HomeIcon from '@material-ui/icons/Home';
import Sidebaroptions from './sidebaroptions';
import SearchIcon from '@material-ui/icons/Search';
import NotificationsIcon from '@material-ui/icons/Notifications';

export default function Sidebar() {
    const vals = [['Home', <HomeIcon />],['Explore', <SearchIcon />], ['Notifications', <NotificationsIcon />]]
    return (
        <div className='sidebar'>
            {
                vals.map(e => {
                    return (
                        <Sidebaroptions text={e[0]} icon ={e[1]} />
                    )
                })
            }
     </div>
        )
};
//SidebarOptions component
import React from 'react';
import './sidebaroptions.css'

export default function Sidebaroptions({text, Icon}) {

    return (
        <div className='sidebar-option'>
            <Icon />
            <h2>{text}</h2>
        </div>
    )
}

There should be absolutely no problem passing an icon as a prop.

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object

This is typically a React error telling you that something you are trying to render as a component is not a valid component, that it’s not a class or a function returning JSX. It is telling you that it is an object, so you are trying to render and object.

One thing that I’m confused by,

<Sidebaroptions text={e[0]} icon ={e[1]} />

and

export default function Sidebaroptions({text, Icon}) {

Is it “Icon” or “icon”. I would expect Icon to be undefined.

My first step in debugging this would have been to console.log that out to see what it is.

1 Like

It’s Icon with a capital “I”,
And I figured out the error. Instead of trying to render <Icon /> as a component I needed to do {Icon}. Now it works. Thanks for you help

1 Like

I see that makes sense.

I still don’t understand how Icon is not undefined in the code you showed, but whatever.

I suspect that if you stored/passed it as HomeIcon instead of as <HomeIcon />, then it would work OK. That’s actually how I would have done it, but I’m not sure that your way is wrong, per se.

Thanks again, I will try your approach too

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.