Resize while keeping the aspect ratio #826
Unanswered
loureirorg
asked this question in
Q&A
Replies: 1 comment
-
Thanks a lot for providing an elaborate explanation as well! Helped me out for a personal project of mine |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Here's how to set SVGR to resize SVGs while keeping the aspect ratio.
.svgrrc.js
file:TL;DR;
I installed SVGR and tried to use it out of the box, but I had some issues:
Resizing
To enable resizing, I found that the
<svg>
tag has to have aviewBox
property to keep the aspect ratio when resizing.But even when the SVG has the property, SVGR removes it by default, making the image impossible to resize.
To fix this, I enabled the
icon
option on webpack, which keeps theviewBox
:Resizing using only
height
orwidth
Enabling the "icon" option makes the SVG resizable, but you have to provide both "width" and "height" properties. If you don't, the image will have
1em x 1em
(16px x 16px
), "contained" mode.To resize the SVG, specify one of the properties (height or width) and set the other to "auto".
Example:
Fixing the positioning being off
When you set the width to "auto", the width may get all space available (or none). This won't deform the image but will get more or less space than needed, shifting the other elements.
To fix this, I had to wrap the SVG into a div:
Using a template to automate the
<div>
wrappingThinking about better ways to wrap the SVG images into
<div>
tags, I found thetemplate
option that applies a template to all imported SVGs:And set the
template
option:Now, you can call it like this:
If you need to set a custom class for the wrapper, use the
containerClassName
property.The
dimensions: false
optionAfter all that, I found the option
dimensions: false
keeps the "viewBox" just like the "icon: true" option. But it also removes the height/width.Without a width, we don't need to set "width=auto". That means the positioning doesn't go off, we don't need to wrap the SVG in a div, and the template is not necessary.
Conclusion
All we need for resizable SVGs is to set
dimensions: false
and nothing else. No need for templates or whatever.I posted this discussion when I didn't know about that and would remove it, but GitHub doesn't allow. So, I'm leaving it here in case this can help anyone.
Beta Was this translation helpful? Give feedback.
All reactions