2
votes

Following the create-react-app doc, I imported a svg as a react component.

However, I can't seem to resize or position it properly, whether it's inline or through css.

I want to scale the SVG component to the same size as my other icon of 100px by 100px, then position at the bottom center of the screen.

I tried setting a width and height props for the svg component.

<IconClose
  className="bubbleBin"
  alt="close bubble"
  height="100px"
  width="100px"
  // viewBox="0 0 100 100"
/>

and in css.

.bubbleBin {
  display: flex;
  position: absolute;
  pointer-events: none;
  align-items: center;
  align-self: center;
  justify-content: flex-end;
}

Here's the minimal code to reproduce it. Full code in Sandbox if needed.

...
import { ReactComponent as IconClose } from './assets/icon_close.svg';

function App() {
  const ICON_WIDTH = 100;
  const ICON_HEIGHT = 100;

  return (
    <div style={{ display: 'flex' }}>
       <img
         src={require('./assets/cat_icon.png')}
         width={String(ICON_WIDTH)}
         height={String(ICON_HEIGHT)}
         alt="cat icon"
         draggable={false}
       />
      <IconClose
        className="bubbleBin"
        alt="close bubble"
        height="100px"
        width="100px"
      />
    </div>
  );
}

I expect the svg to be the same size as my cat icon but this is the result instead. svg styling problem in react

Thank you.

2

2 Answers

1
votes

The viewBox of your SVG just has extra space around it. I quickly eyeballed a new viewbox for you. Try this:

<IconClose
  className="bubbleBin"
  alt="close bubble"
  height="100px"
  width="100px"
  viewBox="9 9 26 26"
/>

Here is a forked project with the change.

https://codesandbox.io/s/issue-styling-svg-component-8wwtw

These values seem to work nicely, you may be able to tweak them a bit more, if you need to use decimal values that's generally fine (9.5 for example).

1
votes

It has nothing to do with React. SVG image has a predefined width and height from the viewBox, and will not scale with the width/height properties as a result. You can read more about how SVG images work here.

Your two options are to use transform: scale(X) on the image which is a bit of a hack, or you can check out this question to see how to properly change the SVG image viewBox. This is a much better option than transforming the image, but I provided both examples to give an understanding of why you're having an issue with width/height.