UNPKG

expo-svg-uri

Version:
61 lines (60 loc) 1.75 kB
import { jsx as _jsx } from "react/jsx-runtime"; import React from "react"; import { Image } from "react-native"; import { SvgCss } from 'react-native-svg/css'; import { isValidSvg } from "./utils"; const SvgUri = (props) => { const { source, xml } = props; const [loading, setLoading] = React.useState(true); const [xmlData, setXmlData] = React.useState(null); React.useEffect(() => { setLoading(true); if (xml) { if (isValidSvg(xml)) { setXmlData(xml); } else { onError('Please provide a valid svg xml'); } setLoading(false); } else if (source) { const { uri } = Image.resolveAssetSource(source); fetchSvg(uri); } else { onError('Please provide a valid svg xml or a source'); setLoading(false); } }, [xml, source]); const onError = (error) => { props.onError && props.onError(new Error(error)); }; const fetchSvg = async (uri) => { try { const response = await fetch(uri); const data = await response.text(); if (isValidSvg(data)) { setXmlData(data); } else { onError('Please provide a valid svg xml'); } setLoading(false); } catch (e) { onError('Failed to fetch svg: ' + e); setLoading(false); } }; if (loading) { return props.loading ?? null; } else if (xmlData) { return _jsx(SvgCss, { xml: xmlData, ...props }); } else { return props.fallback ?? null; } }; export default SvgUri;