Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Use the Material UI IconButton Component

Would you like to add icons to components on your web project? Using icons improves the look and feel of your website. Making it more appealing to end users.

The Material UI icon button component provides a library with many icons that you can integrate into any part of your project.

In this tutorial, we’ll explain all there is to know about icon buttons and then show you real-world examples of how it’s often used on websites. Let’s begin.

Key Features

Before we begin, let’s briefly highlight the key features that make Material UI’s IconButton a must-have in your developer toolkit:

  • Icon Integration: It lets you easily incorporate icons into your user interface.

  • User Interaction: With it, you can handle user interactions like clicks or hovers effortlessly.

  • Styling and Theming: Seamlessly adapt to your project’s design using Material UI’s theming system.

  • Integration with Other Components: Blend IconButton with other Material UI components for a unified look and feel.

Now, let’s get started with using the IconButton element.

Getting Started With React and Material UI

React is one of the most popular frontend web frameworks. It encourages modern web development practices by allowing you to build reusable components for any part of your website.

Material UI is a library that provides building blocks for web projects built using React. It includes ready-made components that make it easy to style your website with minimal code. Thereby allowing you to focus more on building out the logic for your site.

Speaking of saving development time, PureCode provides over 10k ready-made templates to speed up your workflow and ensure your projects are launched on time and schedule. These templates integrate well with frontend libraries like Material UI and Tailwind CSS.

Get Started With PureCode

Prerequisites

Before we begin, make sure you have the following prerequisites in place:

  • Basic knowledge of React and JavaScript.

  • Node.js and npm (Node Package Manager) are installed on your development machine.

Installing React and Material UI

If you haven’t already set up a React project, here are the steps to get you started:

Create a new React project using create-react-app or your preferred setup.

npx create-react-app mui-icon-example

Once the installation completes, use the command below to navigate into the program directory.

cd mui-icon-example

Next, we’ll need to install Material UI and the icons library as a dependency for our project.

npm install @mui/material @mui/icons-material

After the process is completed, open the project with a code editor.

Using the MUI IconButton Component

Using IconButton is straightforward. Here’s a basic example to create a clickable button with a built-in Material UI icon:

import IconButton from '@mui/material/IconButton';
import AddIcon from '@mui/icons-material/Add';

function MyIconButton() {
  return (
    <IconButton color="primary" aria-label="add">
      <AddIcon />
    </IconButton>
  );
}

export default MyIconButton;

In this example, we created an IconButton displaying a “plus” icon. The color property sets the button’s color, and the aria-label provides accessibility for screen readers.

Here is how the page will look when you run your dev server.

Icon b

Props and Options

Material UI’s IconButton element offers a range of props and options to enhance its behavior and appearance. Here are some commonly used ones:

color

The color prop sets the color of the IconButton. It can accept values like “default,” “primary,” “secondary,” or any valid CSS color (e.g., “#FF5722”). Here is an example code.

{/* Example with different colors */}
<IconButton color="default" aria-label="default-button">
  <EditIcon />
</IconButton>
<IconButton color="primary" aria-label="primary-button">
  <DeleteIcon />
</IconButton>
<IconButton color="secondary" aria-label="secondary-button">
  <DeleteIcon />
</IconButton>
<IconButton color="success" aria-label="success-button">
  <DeleteIcon />
</IconButton>
<IconButton color="error" aria-label="error-button">
  <DeleteIcon />
</IconButton>
MUI Icon theme colors

disabled

The disabled prop makes the IconButton unclickable when set to true. It’s commonly used to indicate that a particular action is not available. To disable an icon button component, simply add the disabled prop to it. Here is an example.

{/* Example with a disabled button */}
<IconButton disabled color="primary" aria-label="disabled-button">
   <EditIcon />
</IconButton>

size

The size prop allows you to adjust the size of the IconButton. It accepts values like “small,” “medium” (default), or “large.” Here is an example implementation.

{/* Example with different sizes */}
<IconButton size="small" color="primary" "aria-label="small-button">
   <EditIcon />
</IconButton>
<IconButton size="medium" color="primary" aria-label="medium-button">
   <DeleteIcon />
</IconButton>
<IconButton size="large" color="primary" aria-label="large-button">
   <EditIcon />
</IconButton>

onClick

The onClick prop allows you to define a function that will be executed when the IconButton is clicked. This function handles user interactions with the button.

const handleClick = () => {
  // Your code to handle the click event
  console.log('Item has been Deleted')
};

<IconButton onClick={handleClick} aria-label="clickable-button">
  <DeleteIcon />
</IconButton>
icon button with onclick event handler

Once you click on the icon, you’ll see the text we added to the function logged in the console.

Icon event logged to the console

Styling the Icon Button

We already covered how to use material UI component props to update the look and feel of Icon Buttons. In addition to the default theme styles, you can use the sx prop to add your own custom styles to the icon. For example, let’s create a delete icon button with a custom theme color.

import DeleteIcon from '@mui/icons-material/Delete';

<IconButton sx={{color: '#ffd709'}} aria-label="clickable-button">
  <DeleteIcon />
</IconButton>

In the code above, we are passing the sx property to the icon button component. Then within the curly braces, we use the color parameter to update the color with a custom color.

You can add multiple styles to the sx property. Just make sure to separate each style with a comma.

Here is what the code looks like in the frontend.

Custom color icon button

If you need additional guidance with using the custom styling prop, be sure to check out MUI’s official documentation. Also see the video below for a visual walkthrough.

Adding IconButton to Other Material UI Components

You can use Icon Buttons in conjunction with other MUI components to add interactive icons for actions like opening a drawer, toggling a menu, or navigating. In this section, we’ll show 3 examples of using the icon buttons with other MUI components

Sidebar Drawer Example

For this example, we’ll create a slide-in sidebar navigation menu. When the user clicks on the icon, it will open a menu on the side of the page.

import React, { useState } from 'react';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';
import Drawer from '@mui/material/Drawer';

function App() {
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);

  const toggleDrawer = () => {
    setIsDrawerOpen(!isDrawerOpen);
  };

  return (
    <div>
      <IconButton
        color="primary"
        aria-label="open-drawer"
        onClick={toggleDrawer}
        edge="start"
      >
        <MenuIcon />
      </IconButton>
      <Drawer
        anchor="left"
        open={isDrawerOpen}
        onClose={toggleDrawer}
      >
        {/* Content for the Drawer component */}
        <div style={{ width: 250 }}>Menu content goes here</div>
      </Drawer>
      {/* The rest of your application */}
    </div>
  );
}

export default App;

In the code above, we first import the IconButton, MenuIcon, and Drawer components from Material UI.

After that, we create a functional component, App, which manages the state of the Drawer being open or closed using the isDrawerOpen state variable.

Next, we define a toggleDrawer function that toggles the state of the Drawer when the IconButton is clicked.

Within the App component’s return, we place an IconButton with the MenuIcon as the icon, and it’s set to open or close the Drawer when clicked.

Afterward, place the Drawer component below the IconButton. The Drawer component is conditionally rendered based on the isDrawerOpen state variable, and it’s controlled by the onClose function when the user clicks outside the drawer.

Sidebar drawer example

Navbar With Search Icon

In this example, we’ll create a navigation bar with a menu icon and a search icon. For this, create a Navigation.js component and paste the code below into the component.

import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';
import SearchIcon from '@mui/icons-material/Search';
import Button from '@mui/material/Button';

function MuiExample() {
  return (
    <div>
      <AppBar position="static" color="secondary">
        <Toolbar>
          {/* Menu Icon */}
          <IconButton
            edge="start"
            color="inherit"
            aria-label="menu"
            sx={{ display: { xs: 'block', md: 'none' } }} // Show on mobile only
          >
            <MenuIcon />
          </IconButton>

          {/* Logo (Your logo component or text can go here) */}
          <div
            style={{
              flexGrow: 1,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <img
              src="/your-logo.png"
              alt="Your Logo"
              style={{ maxWidth: '100%', height: 'auto' }}
            />
          </div>

          {/* Search Icon */}
          <IconButton
            color="inherit"
            aria-label="search"
            sx={{ display: { xs: 'block', md: 'none' } }} // Show on mobile only
          >
            <SearchIcon />
          </IconButton>
        </Toolbar>
      </AppBar>
      {/* The rest of your application */}
    </div>
  );
}

export default MuiExample;

In the code above, we import the necessary Material UI components, such as AppBar, Toolbar, IconButton, and icons like MenuIcon and SearchIcon.

Inside the AppBar, we use Toolbar to create the navigation bar.

We use two IconButton components for the menu and search icons. The sx prop with display is used to control when these icons are visible. In this case, they are shown on mobile screens (xs) and hidden on medium screens (md).

Note: Make sure to replace the image source and alt tag with the actual logo you intend to use.

Here is how the code looks when you preview the component we just created.

Mobile navigation menu example

This example creates a responsive navigation bar with icons that appear on mobile screens and disappear on larger screens. You can customize it further to suit your application’s design and needs.

Save and Delete Card Content

For this example, we’ll create an MUI Card component that uses the Icon Button with the save and delete icons to render a card that asks users whether to save or delete an item.

Start by creating a new file within your React app and then copying and pasting the code below to the file.

import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import CardActions from '@mui/material/CardActions';
import IconButton from '@mui/material/IconButton';
import SaveIcon from '@mui/icons-material/Save';
import DeleteIcon from '@mui/icons-material/Delete';
import Button from '@mui/material/Button';

function ItemCard() {
  const handleSave = () => {
    // Your code to save the item 
    alert('Item saved!');
  };

  const handleDelete = () => {
    // Your code to delete the item
    alert('Item deleted!');
  };

  return (
    <Card variant="outlined">
      <CardContent>
        {/* Content of the card goes here */}
        <p>This is an item you can save or delete.</p>
      </CardContent>
      <CardActions>
        <IconButton
          color="primary"
          aria-label="Save"
          onClick={handleSave}
        >
          <SaveIcon />
        </IconButton>
        <IconButton
          color="error"
          aria-label="Delete"
          onClick={handleDelete}
        >
          <DeleteIcon />
        </IconButton>
      </CardActions>
    </Card>
  );
}

export default ItemCard;

In the code above, we are importing the following Material UI components: Card, CardContent, CardActions, and the IconButton component. For icons, we’ll use the SaveIcon and DeleteIcon.

Inside the ItemCard component, we define two functions handleSave and handleDelete to handle the save and delete actions. For this example, we are only displaying an alert whenever the user clicks on any of the icons. However, in a real application, you’ll need to replace the alert calls with your logic to save or delete the item.

The Card component contains the content of the card, and we’ve added a simple paragraph for demonstration.

In the CardActions, we use two IconButton components with the SaveIcon and DeleteIcon. These icons are clickable, and when the user clicks them, the handleSave or handleDelete function is called.

Here is how the code looks on the frontend.

This example creates a card that allows users to save or delete an item by clicking the respective icons. You can customize the content and actions as needed for your application.

Tips and Best Practices

To make the most of Icon Buttons, here are some tips and best practices:

  • Use IconButton for actions that benefit from an icon representation.

  • Ensure accessibility by providing appropriate labels and tooltips.

  • Consider a responsive design, adapting the size of the icons for different devices.

  • If you need to create outlined buttons and contained buttons, we suggest using the MUI’s button component instead.

When to Use IconButtons Over the Button Component

The decision to use the Material UI IconButton element over a Button element with an icon specified depends on your specific use case and design preferences. However, here is a general rule of thumb to follow.

Choose IconButton when the primary focus is on the icon and you want to keep the UI compact and visually intuitive. Use a Button component with an icon specified when you need to provide explicit action labels or when your design requires a consistent approach for mixed content elements. The choice depends on the specific user interface and design requirements of your application.

Frequently Asked Questions

Here are answers to some top questions about using MUI IconButton in a React application.

What is Material UI Icon Button used for?

MUI IconButton is used to add clickable icons to your user interface. It’s ideal for actions that require a visual representation, such as adding items or toggling settings.

How can I customize the appearance of an IconButton?

You can customize the appearance of an IconButton using props like color, disabled, and size. You can also apply custom styles using the sx property.

Can I use custom icons with MUI IconButton?

Absolutely! You can use custom icons with IconButton. Simply import your custom icon component to your web component. Then you’ll need to replace the default icon with the one you just imported.

For example, if you have a custom SVG icon in your project, here’s how to use it with IconButton:

Start by importing your custom SVG icon. For this example, we’ll call the custom SVG icon CustomIcon.

import IconButton from '@mui/material/IconButton';
import CustomIcon from './CustomIcon'; // Import your custom SVG icon

Then in your code, you’ll just need to use the custom icon for the IconButton element.

function CustomIconButton() {
  return (
    <IconButton color="primary" aria-label="custom-icon-button">
      <CustomIcon />
    </IconButton>
  );
}

export default CustomIconButton;

In this code, we import your custom SVG icon as CustomIcon and then use it inside the IconButton element just like you would with Material UI’s built-in icons. Make sure that your custom SVG icon is properly formatted and accessible in your project directory.

What’s the difference between IconButton and Button in Material UI?

The primary difference is in the visual representation. IconButton is designed for displaying icons, while Button typically contains text or more complex content.

How can I handle user interactions, such as clicks, with IconButton?

You can use the onClick prop to define a function that runs when the IconButton is clicked. This allows you to handle user interactions efficiently.

Final Thoughts

Material UI’s IconButton is a powerful tool for enhancing the user experience in your web applications. Whether you need to add functional icons, handle user interactions, or maintain a consistent design, you should consider using this component.

In this tutorial, we’ve explained how icon button works with some example code. This should give you the basic knowledge you need to start using the component for your project.

Next, would you like to learn about PureCode’s templates library? PureCode has many ready-made templates that easily integrate with web applications built using MUI and Tailwind CSS.

Access PureCode’s AI-Generated Templates

Other Resources

If you enjoyed this content, then consider checking others from our blog to help you understand Material UI components.

David Ozokoye

David Ozokoye

Software Engineer and Technical Writer