CodeShady
CodeShady

Reputation: 46

How Can I Display SVG Data In React Native?

I have some SVG image data that I would like to import into my React Native App.

Is there any way to take my raw SVG image data and display it without saving it to a file?

I have an api that will create an image based from any given text (coolProgrammer123) and will return the SVG image data.

https://api.kwelo.com/v1/media/identicon/coolProgrammer123?format=base64

Any Ideas? Thanks.

Upvotes: 0

Views: 1853

Answers (1)

Pitaz
Pitaz

Reputation: 286

I'll suggest you try out react-native-svg-uri

import SvgUri from 'react-native-svg-uri';

const TestSvgUri = () => (
  <View style={styles.container}>
    <SvgUri
      width="200"
      height="200"
      source={{uri:'http://thenewcode.com/assets/images/thumbnails/homer-simpson.svg'}}
    />
  </View>
);

UPDATE

Here is a code snippet on how you can use to use axios to get the SVG from the URL and pass it to the Image tag without using the above npm package.

import React, { Component } from 'react';
import { View, Image } from 'react-native';
import axios from 'axios';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      imageUri: ''
    }
  }

  componentDidMount() {
    this.getSvg();
  }

  getSvg = () => {
    let image_base64;
    axios.get('https://api.kwelo.com/v1/media/identicon/coolProgrammer123?format=base64')
      .then(response => {
        image_base64 = response.data;
        this.setState({
          ...this.state,
          imageUri: image_base64
        })
      })
      .catch(function (error) {
        console.log(error);
      });
      return image_base64;
  }

render(){
  return (
    <View>
      <Image
        style={{
          width: 81,
          height: 81,
          resizeMode: 'contain',
          marginTop: 180,
          marginLeft: 20,
          marginRight: 20,
          alignSelf: "center"
        }}
        source={{ uri: this.state.imageUri }}
/>
    </View>
  );
}
};



export default App;

Upvotes: 1

Related Questions