Vector 582.png

문제점

svg파일의 크기를 css로 조절하려면 다음과 같이 코드를 작성해야 한다.

<button class="pagingButton">
  ${ChevronRightIconSVG}
</button>
.pagingButton {
  width: 24px;
  height: 40px;

  svg{
		width: 240px;
	  height: 240px;
	  path {
	    fill: red;
	    stroke: red;
	  }
	}
}

하지만, 동적으로 svg파일의 스타일을 바꾸기 불편해서 React에서 svg파일을 간편하게 다룰 수 있는 방법을 찾아봤다.

우리는 번들러로 vite를 사용하고 있기때문에, React 컴포넌트 처럼 사용할 수 있는 플러그인을 설치했다.

npm: vite-plugin-svgr

yarn add -D vite-plugin-svgr

그리고, vite config파일에 추가해준다.

// vite.config.js
import svgr from "vite-plugin-svgr";

export default {
  // ...
  plugins: [svgr()],
};

그리고, 사용할 svg파일에서 조정하고 싶은 속성에 current 값을 넣어준다.

<svg xmlns="<http://www.w3.org/2000/svg>" width="current" height="current" viewBox="0 0 37 28" fill="none">
  <path d="M4.7 7.10946C5.37945 9.4668 7.45996 13.2718 10.25 13.8818C10.737 13.9883 11.3962 14.2978 11.9 14.1934C12.4915 14.0709 12.8384 12.7934 13 12.4224C13.8423 10.4887 14.8232 8.61168 15.6333 6.66671C16.0707 5.61677 16.7589 3.08294 18.0833 2.68198C18.899 2.43506 19.872 1.85093 20.1333 2.84596C21.032 6.26755 21.6081 9.89549 23.1333 13.1111C23.4534 13.786 24.0418 14.6478 24.2 15.3741C24.2713 15.7013 24.7949 15.0179 25 14.7509C26.3028 13.0556 27.3157 11.156 28.3667 9.30679C29.5831 7.16655 30.7364 4.95819 32.1667 2.94435C32.2408 2.84003 32.8814 1.89478 32.9333 2.00966C34.9692 6.51658 35 11.9738 35 16.8499C35 18.7193 35 20.5886 35 22.458C35 24.8237 34.7078 24.7207 32.3 25.3441C28.0095 26.455 22.9166 25.7048 18.5167 25.7048C15.3873 25.7048 12.2855 26 9.15 26C7.66667 26 6.18333 26 4.7 26C3.76695 26 3.2345 23.5339 3.2 22.7532C2.97968 17.7675 2 13.0253 2 7.99495" stroke="current" stroke-width="3" stroke-linecap="round"/>
</svg>

width, height, stroke에 current를 넣어주었다.

이제, 사용할 컴포넌트에서 다음과 같이 import 해주고 속성값에 원하는 값을 넣어주면 된다.

import LeaderIcon from '../../icon/LeaderIcon.svg?react';

/--생략--/
<LeaderIcon width={20} height={20} stroke="red" />
/--생략--/

그러면 다음과 같이 나타난다!