svg 이미지 불러오기

Tags
image
svg
부연설명
- svg 이미지 불러오기 - width, height 설정 - 색상 설정
 

[1] 설치

1) react-native-svg 설치

$ yarn add react-native-svg $ npx pod-install

2) react-native-svg-transformer 설치

$ yarn add --dev react-native-svg-transformer

metro.config.js 파일 수정 (없다면 생성)

프로젝트 루트 디렉토리에 metro.config.js 파일에 아래 내용 작성
const { getDefaultConfig } = require("metro-config"); module.exports = (async () => { const { resolver: { sourceExts, assetExts } } = await getDefaultConfig(); return { transformer: { babelTransformerPath: require.resolve("react-native-svg-transformer") }, resolver: { assetExts: assetExts.filter(ext => ext !== "svg"), sourceExts: [...sourceExts, "svg"] } }; })();

[2] svg 불러오기

  • 이제 import 해서 컴포넌트처럼 쓰면 됨.
  • width, height 지정도 가능
import React from 'react'; import { View, StyleSheet } from 'react-native'; import Award from './src/assets/images/award.svg'; export default class App extends React.Component { render() { return ( <View style={styles.container}> <Award /> {/* Provide height and width props as per your need. */} <Award height={400} width={300} /> </View> ); } }; const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }, });
notion image

색상 설정하기

1. svg 파일의 fill 또는 stroke 속성값을 currentColor로 바꾼다.

<polygon fill="currentColor" ...>

2. 컴포넌트 호출 시 style={{color:'#색상값'}}으로 색상을 지정한다.

<Code width={30} height={30} style={color: '#fff'} /> <PlusIcon width={30} height={30} color='white' />;

stroke, fill, color 등의 옵션으로도 색상을 변경할 수 있다.

[TypeScript] declaration.d.ts

프로젝트 루트경로가 아닌 곳에 declaration.d.ts 파일을 만들고 다음을 기입한다.
declare module "*.svg" { import React from 'react'; import { SvgProps } from "react-native-svg"; const content: React.FC<SvgProps>; export default content; }

[TypeScript] Custom.d.ts

타입스크립트에서 빨간 줄이 뜨는 것을 방지하기 위해 커스텀 타입을 지정하자.

custom.d.ts 작성

declare module '*.svg' { const content: React.FunctionComponent<React.SVGAttributes<SVGElement>>; export default content; }

tsconfig 수정 (선택)

tsconfig의 include를 사용하여 컴파일될 파일들을 명시적으로 관리하고 있던 경우라면 해당 파일도 컴파일 목록에 추가시켜주도록 한다.
다만, include 옵션을 사용하고 있지 않다면 컨테이너의 전체 파일을 컴파일 목록에 넣으므로 별도로 작성하지 않아도 알아서 인식된다.
"include": ["src/components", "src/custom.d.ts"]