Reputation: 1634
How can I make sure that the entire SVG will be visible inside the view box? I have an SVG with intrinsic size of 167x210 and a react component of this shape
export const SvgIcon: React.FC<SvgIconProps> = (props) => {
const { children, strokeWidth, width = 24, height = 24, className, fill } = props;
return (
<svg
xmlns="http://www.w3.org/2000/svg"
className={className}
fill={fill}
viewBox={`0 0 ${width} ${height}`}
stroke="currentColor"
strokeWidth={strokeWidth}
width={width}
height={height}
>
{children}
</svg>
);
};
so as you can see I set by default width and height to 24 and vie box to be this same size - 0 0 24 24, but when I paste the icon path markup all I can see is a small subset of what I should see, it does not scale down it crops the path.
this is how I use it:
export const LogoDay: React.FC<LogoProops> = ({
width,
height,
variant,
}) => {
return (
<SvgIcon width={width} height={height}>
<path
d="M158 2H1.5V211H158C158 211 182 133.5 158 124C134 114.5 67.5 124 67.5 124V70C67.5 70 138 80.5 158 70C178 59.5 158 2 158 2Z"
stroke="black"
stroke-width="3"
/>
</SvgIcon>
);
};
I tried everything from this article https://css-tricks.com/scale-svg/ tried messing tiwh preserveAspectRatio but nothing seem to be working.
Thanks
Upvotes: 0
Views: 162
Reputation: 176
The viewBox should be a reflection of the max X and Y coordinates of the path, so it can fit inside.
Only the height and width properties of the svg should be fed by the height and width props, and not the viewBox, which needs to be computed from the max X and Y of the path, and also passed as a prop:
<svg
xmlns="http://www.w3.org/2000/svg"
className={className}
fill={fill}
viewBox={viewBox}
stroke="currentColor"
strokeWidth={strokeWidth}
width={width}
height={height}
>
{children}
</svg>
You would need to compute the max X and Y coordinates of the path so that your implementation be something like:
export const LogoDay: React.FC<LogoProops> = ({
width,
height,
variant,
}) => {
const path = "M158 2H1.5V211H158C158 211 182 133.5 158 124C134 114.5 67.5 124 67.5 124V70C67.5 70 138 80.5 158 70C178 59.5 158 2 158 2Z";
return (
<SvgIcon width={width} height={height} viewBox={calcViewBox(path)}>
<path
d={path}
stroke="black"
stroke-width="3"
/>
</SvgIcon>
);
};
Upvotes: 2