Vũ Nguyễn
Vũ Nguyễn

Reputation: 31

Animate static SVG file with react-native-svg

I'm struggling to get react-native-svg animate in React Native. I also tried the method they suggest with react-native-svg-transformation but it didn't suit my case since I'm working with many files and render them dynamically. Here's my render file:

import React from "react";
import { View, Text } from "react-native";
import { SvgXml } from "react-native-svg";
import SvgAssets from "../resources/SvgAssets";
import AssetsHelper from "../common/AssetsHelper";

class ChineseCharacter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      xmlData: "",
    };
  }

  render() {
    const { xmlData, file } = this.state;
    if (xmlData.length === 0) {
      return <View />;
    }

    return (
      <View style={{ flex: 1 }}>
        <SvgXml xml={xmlData} width="200" height="200" />
      </View>
    );
  }

  componentDidMount(): void {
    const { character } = this.props;
    const characterUnicode = character.charCodeAt(0);
    const file = SvgAssets[characterUnicode.toString()];
    AssetsHelper(file)
      .then(result => {
        this.setState({
          xmlData: result,
        });
      })
      .catch(err => console.log(err));
  }
}

export default ChineseCharacter;

AssetsHelper is basically reading the svg file and convert them to string in order to pass to SvgXml. SvgAssets is an object with key as the charCode and value is the file, something like this:

const assets = {
  "11904": require("./svgs/11904.svg"),
  ...
}

Thank in advance.

Upvotes: 1

Views: 1013

Answers (2)

Vũ Nguyễn
Vũ Nguyễn

Reputation: 31

After few struggling hours, I have found a work around for this problem. I don't use react-native-svg anymore, instead I parse the .svg file to string and put it in react-native-webview. Work like a charm!

render() {
    // @ts-ignore
    const { xmlData, file } = this.state;
    if (xmlData.length === 0) {
      return <View />;
    }
    return (
      <View style={{ width: 300, height: 300 }}>
        <WebView
          source={{ html: xmlData }}
          style={{ backgroundColor: "transparent", width: 300, height: 300 }}
        />
      </View>
    );
  }

Upvotes: 1

Vasyl Stokolosa
Vasyl Stokolosa

Reputation: 33

Try to import the svg files inside ChineseCharacter class.

import svgXml11904 from './svgs/11904.svg'

const assets = {
  "11904": svgXml11904,
  ...
}

Upvotes: 0

Related Questions