Svgr: Preserve aspect ratio

Created on 4 May 2019  ·  6Comments  ·  Source: gregberge/svgr

I am wondering if there is a way to preserve aspect ratio in the generated component.

What I mean by this:

  • If only width is specified, height should be calculated to preserve original aspect ratio.
  • If only height is specified, width should be calculated to preserve original aspect ratio.
  • If both width and height are specified, same as before.

Looking at the generated code from the README:

import React from 'react'

const SvgComponent = props => (
  <svg width="1em" height="1em" viewBox="0 0 48 1" {...props}>
    <path d="M0 0h48v1H0z" fill="currentColor" fillRule="evenodd" />
  </svg>
)

export default SvgComponent

Here both width and height are fixed at 1em even though original aspect ratio is 48:1. So using this component, one has to specify both attributes and remember original aspect ratio.

It would be very convenient if I could specify just one.

Is this possible out of the box?

Thank you

question ❓

All 6 comments

Yeah it is possible, you can use font-size css property and it will define both (because of em). Else you have to define width and height together. Aspect ratio should always be a square if you are dealing with --icon option.

Sorry I wasn't maybe clear.

My image is WxH and it's not a square. svgr will generate a component with width={W} and height={H} by default.

I am wondering if there is any way to preserve aspect ratio, if I use my SVG component like so:

<Svg width={54321} />

In this case, I don't want height to be H, but calculated based on width instead.

EDIT: Now I understand better what you're saying... em and font-size could work on web, but not on native.

It is not possible sorry, specify width and height.

I was able to do this by playing with a template to produce:

width={props.width || (props.height * ${aspectRatio}) || ${width}}
height={props.height || (props.width / ${aspectRatio}) || ${height}}

So if neither is specified use from SVG, if one is specified keep aspect ratio, and if both are specified use as is. Not sure if it's something that useful in general.

Yeah you can do it with a template of course.

@alamothe I have the same issue, could you please provide the full template you used at the end?

Was this page helpful?
0 / 5 - 0 ratings