1

I am trying to insert a material-ui icon into my component via prop. Please let me know what I am doing wrong. However, I am not sure how to pass the icon down in JSX, here is my non-working attempt:

This snippet is me trying to pass in the icon as a prop to the Category component:

<Category icon="InboxOutlinedIcon" title="Tomorrow" categoryName="tomorrow" todos= 
{tomorrowTodos} toggleComplete={this.toggleComplete} handleDeleteTodo= 
{this.handleDeleteTodo}/>

The component class:

const Category = ({ title, icon, categoryName, todos, toggleComplete, handleDeleteTodo }) => (
    <div className="td-section">
        <div className="td-category">
            {/* Add Icon here */ }
            <div>{icon}</div>
            <h2 className={categoryName}>{title}</h2>
            
            <p className="td-count">{todos.length} todos</p>
        </div>
        <div className="td-list">
                {todos.map(todo => (
                        <Todo 
                            key={todo.id} 
                            toggleComplete={() => toggleComplete(todo.id)} 
                            onDelete={() => handleDeleteTodo(todo.id)}
                            todo={todo}
                        />
                ))}
        </div>
    </div>
)
export default Category
Brian
  • 187
  • 5
  • 15

2 Answers2

3

Pass the icon as a component instead of a string as materai-ui icons are ready-made icon components:

import InboxOutlinedIcon from 'materai-ui/...';    

<Category icon={<InboxOutlinedIcon />} .../>

in Category component use like this:

const Category = ({ title, icon, categoryName, todos, toggleComplete, handleDeleteTodo }) => (
<div className="td-section">
    <div className="td-category">
        {icon}
        <div>{icon}</div>
        <h2 className={categoryName}>{title}</h2>
        
        <p className="td-count">{todos.length} todos</p>
    </div>
    <div className="td-list">
            {todos.map(todo => (
                    <Todo 
                        key={todo.id} 
                        toggleComplete={() => toggleComplete(todo.id)} 
                        onDelete={() => handleDeleteTodo(todo.id)}
                        todo={todo}
                    />
            ))}
    </div>
</div>
)
export default Category
DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98
Tomer Almog
  • 3,604
  • 3
  • 30
  • 36
0

If passing the icon by reference is a must, you can just wrap it outside:

const Icon = useMemo(() => {
    const Icon = icon;
    return <Icon />;
}, [icon]);

then just use it as <Icon />

Ivan Yulin
  • 794
  • 7
  • 15