Ways to adjust the dimensions of an SVG icon in a React application

Trying to figure out how to display an SVG icon and text on the same line in React and Next.js. After some research, I've managed to achieve it. However, I'm struggling to control the size of the SVG icon in relation to the text. Ideally, I want the icon to be the same size as each character of the text.

Below is a screenshot of how it appears in the browser.

https://i.sstatic.net/0cOup.png

Here is the code I have written, please let me know what I'm doing wrong:

//mysvg.js
import styles from '../styles/svg.module.css'
export function CircleBottomIcon(props) {
  return (<span class={styles['svg-image']}>
    <svg
      width="30"
      height="30"
      viewBox="0 0 30 30"
      xmlns="http://www.w3.org/2000/svg"
      {...props}
    >
      <title>circle-bottom</title>
      <path
        d="M27.5 15c0 6.893-5.608 12.5-12.5 12.5-6.893 0-12.5-5.608-12.5-12.5C2.5 8.107 8.108 2.5 15 2.5c6.893 0 12.5 5.608 12.5 12.5zm2.5 0c0-8.284-6.716-15-15-15C6.716 0 0 6.716 0 15c0 8.284 6.716 15 15 15 8.284 0 15-6.716 15-15zm-15 2.5l-5.625-5.625-1.875 1.91L15 21.25l7.5-7.466-1.875-1.91L15 17.5z"
        fill-rule="evenodd"
      />
    </svg></span>
  );
}

//index.js
import {CircleBottomIcon} from '../components/mysvg'


export default function Home() {
  return (
<span>
1234<CircleBottomIcon></CircleBottomIcon>567890
</span>
  )
}


//svg.module.css

.svg-image {
   display: inline-block; 
   width: 16px;
   height: 16px;
   
  }

Answer №1

In order to maintain consistency, it is recommended to set fixed values for the viewbox parameter and allow for height and width props to be customizable. To achieve this, you can assign default values of 30 to height and width. Here is a snippet of the code:

const { height, width } = props;
<svg
      width={width}
      height={height}
      viewBox="0 0 30 30"
...

By implementing this approach, you will have the flexibility to specify any desired values for height and width when using the svg component.

Answer №2

Make sure that your CSS code targets the correct element with the class .svg-image:

.svg-image {
   display: inline-block;
   svg {
     width: 16px;
     height: 16px;
   }
  }

Answer №3

This recurring issue with utilizing SVGs in React, particularly custom ones, has frustrated me enough to develop a solution. I have created a wrapper that can resize a specified SVG React element to a desired size.

You can find this solution packaged as: react-svg-resizer. It offers a straightforward way to scale any SVG element.

For a demonstration with examples, refer to the following CodeSandbox link: here's codesandbox with demo with examples

import SvgResizer from "react-svg-resizer";

<SvgResizer size={50}>
   <svg
      width="30"
      height="30"
      viewBox="0 0 30 30"
      xmlns="http://www.w3.org/2000/svg"
      {...props}
    >
      <title>circle-bottom</title>
      <path
        d="M27.5 15c0 6.893-5.608 12.5-12.5 12.5-6.893 0-12.5-5.608-12.5-12.5C2.5 8.107 8.108 2.5 15 2.5c6.893 0 12.5 5.608 12.5 12.5zm2.5 0c0-8.284-6.716-15-15-15C6.716 0 0 6.716 0 15c0 8.284 6.716 15 15 15 8.284 0 15-6.716 15-15zm-15 2.5l-5.625-5.625-1.875 1.91L15 21.25l7.5-7.466-1.875-1.91L15 17.5z"
        fill-rule="evenodd"
      />
    </svg></span>
</SvgResizer>

Despite the inner SVG shape being 30x30 pixels, the resized SVG shape in this example will always be 50x50 pixels

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

Arranging DIVs in a vertical layout

Currently, I am working on a design that involves organizing several <DIV> elements in a vertical manner while still maintaining responsiveness. Here are some examples: Wider layout Taller layout I have tried using floats, inline-block display, ...

Using Node.js: directing subdomains to specific ports

I am in the process of developing a fullstack web application with an API as its backend, which will be hosted on a server provided by DigitalOcean. The front-end, built with ReactJS, is running on port 3000 while the backend (Express server - RESTFul API ...

tips for concealing the shadow of a draggable div during the dragging process

I am facing an issue with a draggable div. When I drag the div, the shadow also moves along with it. I want to find a way to hide this shadow while dragging. <div draggable="true" (dragstart)="mousedown($event)" (drag)="dra ...

How to troubleshoot the EXPO_DEBUG problem in React Native

Whenever I try running expo start in my Mac terminal, I encounter an issue with the following message: Could not access packager status at http://localhost:19001/status. Are you sure the packager is running and reachable? Set EXPO_DEBUG=true in your e ...

The size of the Webpack bundle grows with each subsequent build

For my project, I am utilizing webpack to package it as a library. The project consists of a components library, and for each component residing in its own directory under src/ui, I am creating small bundles. Here is an example component structure: src/ ...

Uh oh! This error message is telling us that the component definition is lacking a display name for React.forwardRef

I created a custom checkbox component as shown below: export const CustomCheckbox = forwardRef( ({ indeterminate, ...rest }, ref) => { const defaultRef = useRef() const resolvedRef = ref || defaultRef useEffect(() => { ...

Adjust the width of the TinyMCE Editor to automatically resize based on the content being

Is it possible for TinyMCE to adjust the content within an absolutely positioned container and update the width while editing? <div class="container"> <textarea>This is my very long text that should not break. This is my very long text tha ...

A simple guide on how to easily retrieve the index of a StepConnector in MaterialUI

Currently, I am utilizing a Stepper component and my goal is to style the connectors individually based on their index. The issue of accessing the current step's index within StepConnector was raised in a GitHub thread back in February. A PR was accep ...

Is it possible to create a dynamic route in next.js using multiple slugs in the URL

Is there a way to structure a route with dynamic parts in a predefined format, like /[name]-id[id], for example having routes such as /bob-id303 or /mary-id205? I attempted to create a file called [name]-id[id].js. In the getInitialProps function, I conso ...

Personalized color scheme for calendar td

I am facing an issue with my event calendar where I want to change the background color of td. I came across a helpful solution in this question, but it did not fully solve my problem. When I implemented the following jquery: $('[class*="fc"]'). ...

Is there a way to mount or unmount a React component by pressing a single key?

I am currently developing an application that showcases 3D objects upon pressing certain keys on the keyboard. My goal is to have these objects disappear after 2-3 seconds or once the animation completes. Below is the component responsible for managing th ...

Error encountered when starting Npm: events.js:292 triggers an unhandled exception

As I dive into learning React, I decided to create a new React app using the create-react-app tool. However, upon running npm start after successfully creating the app, I encountered the following error message: events.js:292 throw er; // Unhandled ...

Tips for maintaining consistent image dimensions while resizing your browser window

I'm having trouble preventing an image from resizing when I adjust the browser size. If you click on this link and try resizing your browser, you'll see what I mean - the image stays the same. I've attempted various methods but haven't ...

What is a simple way to exclude a prop from a declaration in a React/TypeScript project in order to pass it as undefined

I'm trying to accomplish this task but encountering a typescript error indicating that the label is missing. Interestingly, when I explicitly set it as undefined, the error disappears, as shown in the image. Here's how my interface is structured ...

Exploring the world of graphql fragment masking with the power of keys

When it comes to developing GraphQL clients, fragment masking is often recommended as a best practice. However, I'm struggling to understand how to implement basic React functionalities with such complexity. A common necessity is providing key propert ...

Unable to resolve 500 error on Vercel in Next.js despite successful local development

Here is the content of route.ts import fs from 'fs'; import path from 'path'; import PizZip from 'pizzip'; import Docxtemplater from 'docxtemplater'; import { NextRequest, NextResponse } from 'next/server'; ...

Implementing multiple condition-based filtering in React Native for arrays

I am looking to apply multiple filters to an array based on certain conditions defined by toggling switches. The issue arises when toggling two or more switches simultaneously, resulting in an empty array. My goal is to retrieve an array containing the tru ...

I am facing an issue where the CSS style sheet is not connecting to my HTML file

I'm facing an issue with linking my CSS style sheet to my HTML file using the following code: <link ref="stylesheet" href="../landing/css/stylesheet.css" type="text/css"/> Even though I have checked the directory l ...

Disable the highlight effect when the mouse moves away from the MUI Autocomplete component

When using the Autocomplete feature and hovering over the list of options, if you move the mouse out of it, the last option that was hovered over remains highlighted. What is the most effective method to remove this highlight when the mouse pointer is no ...

Positioning HTML elements using CSS and avoiding the use of tables

I'm struggling with my clear CSS declarations. This is how I'd like it to appear: View the Fiddle demo HTML: <div id="timesheeteditor"> <div id="weekselector"> <div>Week 1</div> <div>Week 2</div> ...