Programming/React & TypeScript
React에서 svg 파일을 함수 컴포넌트화해서 사용하기
감귤밭호지차
2023. 11. 17. 00:31
React에서 SVG 파일을 함수 컴포넌트화해서 간편하게 관리 및 재사용하고 불러올 수 있게 만들어봅시다.
# 사용 기술 스텍
React x Vite x TypeScript
SCSS
https://www.telerik.com/blogs/how-to-use-svg-react
How to Use SVG in React
SVG is an excellent way to develop scalable and responsive visuals. This article introduces SVGs and different methods of using them in a React application.
www.telerik.com
type SVG = {
fillColor: string;
width: string;
height: string;
};
const SearchIcon = ({ fillColor, width, height }: SVG) => {
return (
<svg
width={width}
height={height}
viewBox="0 0 32 32"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
>
<g
id="Page-1"
stroke="none"
stroke-width="1"
fill="none"
fill-rule="evenodd"
>
<g
id="Icon-Set"
transform="translate(-256.000000, -1139.000000)"
fill={fillColor}
>
<path
d="M269.46,1163.45 C263.17,1163.45 258.071,1158.44 258.071,1152.25 C258.071,1146.06 263.17,1141.04 269.46,1141.04 C275.75,1141.04 280.85,1146.06 280.85,1152.25 C280.85,1158.44 275.75,1163.45 269.46,1163.45 L269.46,1163.45 Z M287.688,1169.25 L279.429,1161.12 C281.591,1158.77 282.92,1155.67 282.92,1152.25 C282.92,1144.93 276.894,1139 269.46,1139 C262.026,1139 256,1144.93 256,1152.25 C256,1159.56 262.026,1165.49 269.46,1165.49 C272.672,1165.49 275.618,1164.38 277.932,1162.53 L286.224,1170.69 C286.629,1171.09 287.284,1171.09 287.688,1170.69 C288.093,1170.3 288.093,1169.65 287.688,1169.25 L287.688,1169.25 Z"
id="search"
></path>
</g>
</g>
</svg>
);
};
export default SearchIcon;
React 컴포넌트에서 해당 SVG 파일을 사용할 때는 원하는 사이즈와 색상을 props 로 전달하면서 사용하면 됩니다.
import SearchIcon from "@/assets/search";
const Header = () => {
return (
<div className="headerWrapper">
<div className="logo">
<SearchIcon
fillColor={"#000000"}
width={"30px"}
height={"30px"}
/>
</div>
</div>
);
};
export default Header;
이쁘게 적용 되었습니다.