Use Inkscape to design a custom icon and then incorporate it into your project using Material UI's Svg

I recently designed an icon using Inkscape. Following the instructions here, I set the viewport to 24x24 and saved it as an SVG file:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   sodipodi:docname="drawing.svg"
   inkscape:version="1.0 (4035a4fb49, 2020-05-01)"
   id="svg16"
   version="1.1"
   viewBox="0 0 6.3499999 6.3499997"
   height="24"
   width="24">
   ...

After creating the SVG file, I tried to use it as a Material UI icon. However, I encountered errors such as 'sodipodi:nodetypes' and issues with the style formatting. I cleaned up the code, leaving only the paths, but the icon still didn't display. I even tried simplifying it to just one path without success.

import React from "react";
import SvgIcon from "@material-ui/core/SvgIcon";

const Logo = (props) => {
  return (
    <SvgIcon {...props}>
      <path
        d="m 4.493643,-24.00 v 3.667168 h 3.166867 V -24.000 Z m 1.366019,0.339834 h 0.434813 v 0.257505 h -0.434813 z"
        id="rect1057" />
    </SvgIcon>
  )
}
export default Logo;

If anyone can provide guidance on the correct process for using this icon or identify any mistakes I may have made, it would be greatly appreciated.

Answer №1

I successfully tackled this issue independently:

  1. Start by creating your icon using inkscape
  2. Save it as "Optimized SVG" and ensure to check Export as SVG 1.1 in the Preference Dialog settings
  3. Make sure to select the following options:
  • Shorten color values
  • Convert CSS attributes to XML attributes
  • Collapse groups
  • Create groups for similar attributes
  1. For the SVG Output:
  • Remove the XML declaration
  • Remove metadata
  • Remove comments
  • Format output with line-breaks and indentation
  1. Save the file and open it, e.g., with nvim
  2. Copy everything between the <svg> tags
  3. Create a new file specifically for the icon (e.g., icon.js)

Here's the code snippet:

import React from "react";
import SvgIcon from "@material-ui/core/SvgIcon";

const MyIcon = ({ color }) => {
  const memorizedIcon = React.useMemo(() => {
    return (
      <SvgIcon viewBox={"0 0 52.916665 52.91667"}>
        // YOUR ICON
      </SvgIcon>
    );
  }, [color]);

  return memorizedIcon;
};

export default MyIcon;
  1. Transfer the viewbox info from the svg file to the code
  2. Change the style annotations from
    style="something-tag: something"
    to
    style={{somethingTag: "something"}}

Voila! Task completed.

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

The higher-order component consistently triggers a rerender, disregarding the use of shouldComponent

Here is an example of a higher order component: // HigherOrderComponent.js const withLogging = WrappedComponent => class extends React.Component { componentDidMount() { console.log('Component has mounted'); } render () { return ...

Similar to the getState() function in react-redux, ngrx provides a similar method in Angular 6 with ngrx 6

Recently, I developed an application with react and redux where I used the getState() method to retrieve the state of the store and extract a specific slice using destructuring. Here's an example: const { user } = getState(); Now, I am transitioning ...

Retrieving information from the backend results in an endless cycle, preventing it from loading successfully

My lack of experience with Async functions is evident in the issue I'm facing. The code to fetch templates from a back-end into React keeps repeating without properly setting the state to the data. import React, { useState} from 'react'; imp ...

Encountered an unhandled runtime error: TypeError - the function destroy is not recognized

While working with Next.js and attempting to create a component, I encountered an Unhandled Runtime Error stating "TypeError: destroy is not a function" when using useEffect. "use client" import { useEffect, useState} from "react"; exp ...

Error: You are not able to utilize an import statement outside of a module when utilizing the `fast-image-zoom` feature

Currently, I am attempting to integrate fast-image-zoom into my React/Next.js application and unfortunately encountering an error message that reads: SyntaxError: Cannot use import statement outside a module at Object.compileFunction (node:vm:353:18) ...

Steps for incorporating redux into a react.js application:

When attempting to implement Redux with functional code in React, I encountered an issue with the `.subscribe()` method. It seems to run multiple times for every state update, resulting in the count of all previous updates plus one. How can I ensure that t ...

Issues may arise in Typescript when trying to return an array of data from a redux createAsyncThunk function

Below is the code I am using to retrieve a list of users: export const fetchUserById = createAsyncThunk( "users/fetchById", async (_, { rejectWithValue, fulfillWithValue }) => { try { const response = await fetch(`https://reqres. ...

What is the best way to display a placeholder image in a React project when the image URL is

Here is the code snippet I'm working with: import React, { Component } from 'react'; import './App.css'; class App extends Component { state = { loaded: false, error: false } onImageLoad = () => { this.setS ...

Redirecting in NextJs based on regular expressions

I'm currently working with Next.js and facing a challenge in redirecting to a specific path based on certain regex conditions and cookie presence. The objective is to redirect to /foo/bar when the source doesn't contain the key bar but has a par ...

Render images conditionally as background elements for the body, ensuring they do not increase the height of pages with minimal content

Incorporating NextJS image components into the RootLayout of a NextJS component with negative z-indexes and absolute positioning was necessary to align them with dynamic content. However, an issue arose when these images at the base route '/' cre ...

The useEffect dependency of useCallback in React always results in a render being triggered

I have an enigma. A custom React hook is in play here that fetches data based on time periods and saves the results in a Map: export function useDataByPeriod(dateRanges: PeriodFilter[]) { const isMounted = useMountedState(); const [data, setData] ...

Is it possible to import a package from a monorepo located in a different repository?

Currently, I have successfully set up a create-react-app and a storybook packages in a lerna monorepo. My goal now is to utilize the components created within the storybook package in an entirely fresh repository. I attempted using npm install git://githu ...

What is the best way to integrate a condition for handling invalid or empty input in a Contact Form when using FormSpree?

Utilizing Formspree to create a basic Contact form on my NextJS site. Formspree offers this React code sample: // Don't forget to execute npm install @formspree/react // For additional assistance, go to https://formspr.ee/react-help import React from ...

Managing value state with several Formik forms within a single component

I'm currently in the process of constructing a web page using React and Formik. Within this form page, I have integrated three distinct Formik forms that are conditionally displayed based on a switch statement. The reason behind structuring it this wa ...

Tips for using regular expressions with the find method in JavaScript?

Welcome to my Object: let data = [{ "title": "User info", "category": "personal", "userId": "abc12345" }, { "title": "Customer Info", "category": ...

Production build encountering unhandled TypeError in proxy

One day, I decided to tweak MUI's styled function a bit, so I came up with this proxy code: import * as muiSystem from '@mui/system'; type CreateMUIStyled = typeof muiSystem.styled; type MUIStyledParams = Parameters<CreateMUIStyled>; ...

Issue with Next.js: Router.push not causing page to refresh

I'm currently developing a next.js page called /page/data/[dataId] (this page is accessed when a user clicks on a link from the page /page/data, where I fetch the list of items through an API). When a user clicks on a button, I make an API call to de ...

Using Unicode JSON in Laravel blade to pass data to React components, encountering an issue with JSON parsing

I currently have a JSON object stored in the database: { "ui": {}, "title": "Hola mundo 2", "values": {}, "properties": {}, "description": "descripcion" } Within the Laravel controller, ...

provide the React Context value as an argument

I'm facing an issue where I cannot pass a context value as a parameter when calling a function from another file. The code I have is shown below: import React, { useContext } from React import { AuthContext } from "src/contexts/AuthContext"; ...

React with Redux: the best approach for managing post-dispatch actions

Within my component, there is internal state such as isLoading that has access to redux data. I would like to dispatch a thunk action (api request) within this component, resulting in a change to the redux data. Once the thunk is completed, I need to updat ...