Skip to content

Commit

Permalink
Add onLoad method to SvgUri (#1817)
Browse files Browse the repository at this point in the history
Co-authored-by: Harvey Connor <[email protected]>
  • Loading branch information
WoLewicki and Harvey Connor authored Jul 26, 2022
1 parent c87f823 commit 24cfaab
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 12 deletions.
34 changes: 25 additions & 9 deletions USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,31 @@ If remote SVG file contains CSS in `<style>` element, use `SvgCssUri`:

```jsx
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"
/>
);
import { ActivityIndicator, View, StyleSheet } from 'react-native';
import { SvgUri } from 'react-native-svg';
export default function TestComponent() {
const [loading, setLoading] = React.useState(true);
const onError = (e: Error) => {
console.log(e.message);
setLoading(false);
};
const onLoad = () => {
console.log('Svg loaded!');
setLoading(false);
};
return (
<>
<SvgUri
width="100"
height="100"
uri="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/ruby.svg"
onError={onError}
onLoad={onLoad}
/>
{loading && <ActivityIndicator size="large" color="#0000ff"/>}
</>
);
}
```

## Error handling
Expand Down
2 changes: 2 additions & 0 deletions src/index.js.flow
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,8 @@ export type UriProps = {
uri: string | null,
onError?: (error: Error) => void,
override?: SvgProps,
onError?: (error: Error) => void,
onLoad?: () => void,
...
} & SvgProps;
export type UriState = {
Expand Down
14 changes: 11 additions & 3 deletions src/xml.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export interface JsxAST extends AST {
export type AdditionalProps = {
onError?: (error: Error) => void;
override?: Object;
onLoad?: () => void;
};

export type UriProps = SvgProps & { uri: string | null } & AdditionalProps;
Expand Down Expand Up @@ -132,11 +133,18 @@ export async function fetchText(uri: string) {
}

export function SvgUri(props: UriProps) {
const { onError = err, uri } = props;
const { onError = err, uri, onLoad } = props;
const [xml, setXml] = useState<string | null>(null);
useEffect(() => {
uri ? fetchText(uri).then(setXml).catch(onError) : setXml(null);
}, [onError, uri]);
uri
? fetchText(uri)
.then((data) => {
setXml(data);
onLoad?.();
})
.catch(onError)
: setXml(null);
}, [onError, uri, onLoad]);
return <SvgXml xml={xml} override={props} />;
}

Expand Down

0 comments on commit 24cfaab

Please sign in to comment.