React Native에서 Typescript와 함께 SVG 다루기

쫀구·2023년 9월 22일
post-thumbnail

SVG는 웹에서 자주 사용되는 벡터 그래픽 포맷입니다. 이 글에서는 React Native에서 Typescript를 이용해 SVG를 어떻게 활용하는지 살펴보겠습니다.

SVG 예시:

<svg width="16" height="21" viewBox="0 0 16 21" fill="none" 
xmlns="http://www.w3.org/2000/svg">
<path d="M15.3 ..." stroke="#sdsdsd" stroke-width="2"/>
</svg>

먼저, SVG에 접근하기 위해 프로젝트의 src/custom.d.ts 파일을 생성합니다.

// src/custom.ts

declare module '*.svg' {
  import React from 'react';
  import {SvgProps} from 'react-native-svg';
  const content: React.FC<SvgProps>;
  export default content;
}

위와 같이 코드를 작성하면 접근할 준비가 되었고 모든 svg 파일이 src/assets/icon 디렉토리에 위치한다고 가정하겠습니다.

  • SVG의 크기, 색상, 라인 등의 속성을 유동적으로 변경하려면, fill, stroke, stroke-width 값을 조정해야 합니다.

  • fill과 stroke의 기본 값을 currentColor로 설정하여, 상위 컴포넌트의 색상을 따르게 만들 수 있습니다. 그리고 stroke-width는 유동적으로 값을 변경할 경우에만 지정하면 됩니다.

변경 전 SVG:

<svg width="16" height="21" viewBox="0 0 16 21" fill="none" 
xmlns="http://www.w3.org/2000/svg">
<path d="M15.3 ..." stroke="#sdsdsd"
 stroke-width="2"/>
</svg>

변경 후 SVG:

<svg width="16" height="21" viewBox="0 0 16 21" fill="currentColor" 
xmlns="http://www.w3.org/2000/svg">
<path d="M15.3 ..." stroke="currentColor"/>
</svg>

⚙️ SVG 속성 조정하기

검색 아이콘을 사용한 예시

❓ 크기

  • 크기: SVG의 너비와 높이를 조정합니다.
import SearchIcon from 'src/assets/icon/searchicon.svg';

const Componet = () => {
	
  return (
			<Container>
				...
				<SearchIcon width="50px" height="50px" />
			</Container>
	)
}

❓ 라인

strokestrokeWidth 값을 이용해 라인의 색상과 굵기를 조절합니다.

import SearchIcon from 'src/assets/icon/searchicon.svg';

const Componet = () => {
	
  return (
			<Container>
				...
				<SearchIcon    
                  width="50px"
                  height="50px" 
                  stroke="#bd3333"
                  strokeWidth="3" 
				/>
			</Container>
	)
}

❓ 색상

  • color 속성을 이용해 SVG의 색상을 변경합니다. (참고로 fill이 아닌 color를 사용해야 합니다.)
import SearchIcon from 'src/assets/icon/searchicon.svg';

const Componet = () => {
	
  return (
			<Container>
				...
				<SearchIcon    
                  width="50px"
                  height="50px" 
                  color="#33abbd"
				/>
			</Container>
	)
}

이러한 방식으로 React Native와 Typescript에서 SVG를 유동적으로 활용할 수 있습니다.

profile
Run Start 🔥

0개의 댓글