github.com/react-native-svg/react-native-svg

 

react-native-svg/react-native-svg

SVG library for React Native, React Native Web, and plain React web projects. - react-native-svg/react-native-svg

github.com

매번 assets 폴더에서 import 해오다가 svg 라이브러리를 사용해봤습니다.

 

일단 위에 설명이 있지만 다시한번 사용법을 적어봅니다. 

 

yarn add react-native-svg

expo install react-native-svg

npm install react-native-svg

를 통해 라이브러리를 설치합니다.

 

react-native 0.60 이상을 오토링크가 되므로 환경세팅을 할 필요가 없어서 바로 import 시켜서 사용하면 됩니다.

만약 이하 버전을 사용하면 위 링크에 들어가 세팅을 해줍니다.

 

import Svg, {
  Circle,
  Ellipse,
  G,
  Text,
  TSpan,
  TextPath,
  Path,
  Polygon,
  Polyline,
  Line,
  Rect,
  Use,
  Image,
  Symbol,
  Defs,
  LinearGradient,
  RadialGradient,
  Stop,
  ClipPath,
  Pattern,
  Mask,
} from 'react-native-svg';

/* Use this if you are using Expo
import * as Svg from 'react-native-svg';
const { Circle, Rect } = Svg;
*/

import React from 'react';
import { View, StyleSheet } from 'react-native';

export default class SvgExample extends React.Component {
  render() {
    return (
      <View
        style={[
          StyleSheet.absoluteFill,
          { alignItems: 'center', justifyContent: 'center' },
        ]}
      >
        <Svg height="50%" width="50%" viewBox="0 0 100 100">
          <Circle
            cx="50"
            cy="50"
            r="45"
            stroke="blue"
            strokeWidth="2.5"
            fill="green"
          />
          <Rect
            x="15"
            y="15"
            width="70"
            height="70"
            stroke="red"
            strokeWidth="2"
            fill="yellow"
          />
        </Svg>
      </View>
    );
  }
}

 

이렇게 Circle, Ellipse, G, Text, TSpan, TextPath, Path, Polygon, Polyline, Line, Rect, Use, Image, Symbol, Defs, LinearGradient, RadialGradient, Stop, ClipPath, Pattern, Mask 같은 도형 같은 것들도 사용할 수 있네요 SVG로

 

저는 웹에서 svg를 불러오는 용도로 사용할거라서

import * as React from 'react';
import { SvgCssUri } from 'react-native-svg';

export default () => (
  <SvgCssUri
    width="100%"
    height="100%"
    uri="http://thenewcode.com/assets/svg/accessibility.svg"
  />
);

이 방법으로 사용했습니다.

 

저 같은 경우는 클릭했을 때 브라우저를 띄워주고 싶어서

 <TouchableOpacity onPress={() => Linking.openURL('https://www.naver.com/')}>
       <SvgCssUri width="160" height="60" style={styles.ImgStyle} uri="https://s1.econotimes.com/assets/images/econotimes/mobile/about/imgLogoNaver.svg"/>
 </TouchableOpacity>

이렇게 사용했습니다.

 

그러면 네이버 svg 로고가 나올 것이고 로고를 클릭했을 때 react-native의 내장 함수인 Linking으로 naver가 핸드폰 브라우저에 뜹니다. 

스타일은 width, height를 줄 수 있고 스타일드컴포넌트를 사용할 경우 style= { styles.스타일 이름 }으로 주셔도 됩니다.

 

+ Recent posts