How can you give a custom icon to the 'startIcon' of a MaterialUI button?

Below is the current code I am using:

import {
  Button,
  Grid,
  Typography,
  } from '@material-ui/core';

import EditOutlinedIcon from '@material-ui/icons/EditOutlined';

<Grid item>
     <Button
        variant="outlined"
        className={classes.button}
        onClick={toggleState('showEdit')}
        startIcon={<EditOutlinedIcon />}
     >
     Edit
     </Button>
</Grid>

I am seeking a way to customize the icon assigned to startIcon, rather than using the default EditOutlinedIcon from material-ui.

UPDATE:

After implementing @Peter Ambruzs's suggestion with an inline SVG, it worked successfully. However, when attempting the same approach by linking the code to an icon located in the src/assets folder, only the file path is displayed on the button as shown below:

https://i.sstatic.net/YLvHj.png

The code I used for this scenario:

import {
  EditIcon,
} from '../../../assets/icons';

 <Grid item>
            <Button variant="outlined" startIcon={EditIcon}>
                   custom
            </Button>
 </Grid>

The icon in question can be found at this location:

https://i.sstatic.net/gTZiM.png

The index.js file contains the following code:

export { default as EditIcon } from './edit.svg';

The edit.svg file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 24.0.1, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
... (SVG code content)

Answer №1

To generate an image using SVG as the source, you can follow this example:

import React from "react";
import { Button, Grid } from "@material-ui/core";
import EditOutlinedIcon from "@material-ui/icons/EditOutlined";
import Icon from "@material-ui/core/Icon";

export default function App() {
  const svgImage = (
    <Icon>
      <img alt="edit" src="edit.svg" />
    </Icon>
  );

  return (
    <div className="App">
      <Grid item>
        <Button variant="outlined" startIcon={svgImage}>
          custom
        </Button>
        <Button variant="outlined" startIcon={<EditOutlinedIcon />}>
          Edit
        </Button>
      </Grid>
    </div>
  );
}

https://codesandbox.io/s/peaceful-jepsen-eo3td

Answer №2

Adding a width style to the img tag can help downscale the svg icon. This is a small improvement on Peter Ambruzs' code.

    import React from "react";
    import { Button, Grid } from "@material-ui/core";
    import EditOutlinedIcon from "@material-ui/icons/EditOutlined";
    import Icon from "@material-ui/core/Icon";

    export default function App() {
  enter code hereconst svgIcon = (
    <Icon>
      <img alt="edit" src="edit.svg" style={{width: "100%"}}  />
    </Icon>
  );

  return (
    <div className="App">
      <Grid item>
        <Button variant="outlined" startIcon={svgIcon}>
          custom
        </Button>
        <Button variant="outlined" startIcon={<EditOutlinedIcon />}>
          Edit
        </Button>
      </Grid>
    </div>
  );
}

Answer №3

To transform your local SVG into a React Component, you simply need to import it in a different manner.

import { ReactComponent as CustomIcon} from '../../../assets/icons/custom.svg';

After importing, you can then utilize it as a component.

<Button variant="outlined" startIcon={<CustomIcon />} >
      Custom
</Button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to display an alert when the button is clicked repeatedly?

Is it possible to keep displaying the alert every time we click the button, rather than just once after clicking it? I currently have an alert set to trigger when a button is clicked, but it disappears after 3 seconds. How can I make it show up again with ...

The standard color code applied to an HTML button

I need to create an anchor element <a> that resembles an HTML button. However, I am struggling to find the default background color for the input type button. ...

What are some techniques to avoid page refresh after uploading a file to the development server?

I am currently facing an issue with my React application, where it is running on port 3000 and the development server on port 5000. There is a form in the application that sends data to a remote API and uploads a file to my dev server at /upload.do and the ...

The slider's border-radius is not being maintained as it moves from left to right

We recently implemented a slider on our website, located at . While we added a border-radius to the slider, we noticed that when the images slide, the border-radius is slightly removed... I attempted to contain the parent element with overflow: hidden, bu ...

Check the duration of user activity on my app. For example, "Sarah has been active for 15 minutes."

Is there a way to display the duration of a user's online activity? In the messaging app header, it should read: "David has been active for 12 minutes", and this information needs to be saved in local storage. I am facing challenges in co ...

Define the width of jqgrid

I have been utilizing SmartAdmin jqgrid to showcase data in tabular format. The number of columns in the datatable changes dynamically each time. I am converting the DataTable to a JSON object and assigning it to the jqgrid. However, it appears that jqgrid ...

Stopping jQuery fadeOut from setting the display property to 'hidden'

I am currently working on a project that involves creating a lightbox effect. I am using jQuery's fadeIn and fadeOut functions to display enlarged div elements. However, I have encountered an issue - when I use fadeOut on the enlarged div, the smaller ...

Error message: The 'Access-Control-Allow-Origin' policy is preventing access in a react express docker application

I have successfully set up a front-end React application and a Node/Express API using Docker. The React app is currently running on localhost:3000, while the API is running on localhost:9000. Both applications are fully functional. However, I am encounteri ...

The function fromEvent is throwing an error stating that the property does not exist on the type 'Event'

I'm attempting to adjust the position of an element based on the cursor's location. Here is the code I am currently using: this.ngZone.runOutsideAngular(() => { fromEvent(window, 'mousemove').pipe( filter(() => this.hove ...

The concept of asynchronous behavior in ReactJS using the useState hook

I am working on a page to display a list of products. I have included an input file button that allows users to select multiple images. After selecting the images, I use an API to upload them to the server and show the progress visually in the UI with the ...

Using hyperlinks in ChartJS bars within a React application

I am currently utilizing chartjs-2 within a react functional component. If you would like to view the code, please follow this link: https://codesandbox.io/s/elastic-brook-okkce?file=/src/Dashboard.jsx In my implementation, I have displayed 4 bars and I a ...

Tips for applying styles to elements that are not directly related when the parent element has a specific class using CSS

I have some HTML code structured as shown below. <div class='A'> <div class='B' /> <div class='C' /> </div class='A'> <div class='D' /> My Objective: If A contains C: ...

Troubleshooting Problems with CSS Three-Column Layout

Struggling with aligning domain names in a 3 column setup, I have been attempting this for some time now without success. I am new to this and could use some guidance. Here is the code: TPL file <div> <p class="center">{foreach key=num it ...

Modify the CSS using JavaScript after a brief delay

I'm creating a homepage that includes animations. Inside a div, I initially have display: none, but I want it to change to display: block after a few seconds. I've been trying to use JavaScript for this purpose, but I'm struggling to find th ...

Limiting the number of characters in PHP/MySQL

Here is a glimpse into the scenario I am currently facing: The content, including the heading, text, and image, is all dynamically generated based on user input. Users have the option to include an image and choose the text for both the heading and main c ...

I encountered an unexpected token error while using JavaScript syntax with objects

In my current coding project, I have encountered an issue while attempting to utilize an object from a different JavaScript file. Despite importing the necessary function from this external file, there seems to be a syntax error present. Can anyone offer ...

Error: The attempt to push certain references to 'https://git.heroku.com/readingcom.git' failed

! [remote rejected] master -> master (pre-receive hook declined) I've encountered an issue while trying to deploy this app from a git repository on Heroku. I keep getting the pre-receive hook declined error. Please see below for the detailed erro ...

Is it possible for Hyperloop to function effectively using the latest Async/Await technology?

After visiting , I noticed that their examples illustrate making a fetch as a wrapper around priomsies. I understand that in JavaScript, async/await is syntactic sugar around promises. However, I am interested to know if I can apply the async/await patter ...

Center the div element and adjust its scale to perfectly fit the screen

I have been struggling to optimize my website for mobile devices by centralizing the content display. When I access it on a mobile device through , there is excessive space below the content, forcing me to pinch zoom in order to read properly. How can I el ...

"Seamlessly transition between slides in React Native snap carousel with no pause

Apologies for the vague title, I struggled to find the right words to describe my issue. Currently, I am incorporating React-native-snap-carousel (3.9.1) into my EXPO application to create a simple carousel. When navigating between slides, there is no de ...