Problem displaying SVG images in React Native - react-native

I'm having trouble displaying an SVG image in my React Native app. When I try to display it in my React Native app, it gets distorted and doesn't look as expected.
Here is how the image should appears:
And here is how it looks in my React Native app:
I've included the SVG image file that I'm using here: [file attachment]
To display the image I tried the following both method:
import AltoDark from '#/assets/image/profil/alto_dark.svg';
...
<View>
//first method
<AltoDark/>
// second method
<SvgXml xml={AltoDark} />
</View>
my package.json is the following one
"react-native-svg": "10.1.0",
"react-native-svg-transformer": "^1.0.0",
and my metro config is
const {getDefaultConfig} = require('metro-config');
module.exports = (async () => {
const {
resolver: {sourceExts, assetExts},
} = await getDefaultConfig();
return {
transformer: {
babelTransformerPath: require.resolve('react-native-svg-transformer'),
},
resolver: {
assetExts: assetExts.filter(ext => ext !== 'svg'),
sourceExts: [...sourceExts, 'svg'],
},
};
})();
The svg file can be found here: https://pastebin.com/kPW2Qr32. Anyone suggest what might be causing this issue and how I can fix it so that the image looks correct in my React Native app?

In my svg file i change the objectBoundingBox dimension. I went from 1x1 to 2x2. Then I played with the before last argument of the transform="matrix()" to adjust the horizontal position of the image. I went from 0.160427to 0.760427
<pattern id="pattern0" patternContentUnits="objectBoundingBox" width="1" height="1">
<use xlink:href="#image0_595_4081" transform="matrix(0.00191705 0 0 0.000715206 0.160427 0.0851681)"/>
</pattern>
<pattern id="pattern0" patternContentUnits="objectBoundingBox" width="2" height="2">
<use xlink:href="#image0_595_4081" transform="matrix(0.00191705 0 0 0.000715206 0.760427 0.0851681)"/>
</pattern>

I follow the below steps while using an SVG image in React Native app.
Convert SVG to JSX element from here.
Create a .tsx file and paste the JSX element.
Give a desirable name & export the JSX element as a functional component.
Use it like this in your component.
import AltoDark from '../../components';
...
...
<AltoDark/>

Related

Lottie ref in Expo (react native)

I am trying to move my existing React Native (typescript) project to Expo. Everything is working fine in Expo except modal with Lottie animation ( without expo it is working properly).
My code:
export const SuccessModal = ({isVisible = false, onAnimationFinish}: Props) => {
let animation: any = React.createRef();
useEffect(() => {
if (isVisible) {
animation.current.play();
}
}, []);
return (
<Modal
visible={isVisible}
backdropStyle={{backgroundColor: 'rgba(230, 228, 253, 0.5)'}}>
<LottieView
ref={animation}
source={require('../assets/success-lottie.json')}
style={{width: 300, height: 300}}
autoPlay={true}
loop={false}
onAnimationFinish={onAnimationFinish}
/>
</Modal>
);
};
I guess the problem is with ref={animation} , because modal is being displayed, but animation is not moving - seems like animation.current.play() is not invoked in the effect. I tried useRef(null) and useRef<LottieView | null>(null) as suggested in other posts. Also tried to reinstall lottie with command: expo install lottie-react-native.
Any ideas what might be wrong here? What is so specific for Expo?
I think calling animation.current.reset(); before animation.current.play(); would do the trick.
I am using const animation = useRef(null) hook and got it working with Expo too.
However, initial play() was not working by default and I had did this trick to make it work as soon as component loads.
...
const animation = useRef(null);
...
useEffect(() => {
animation.current?.reset();
animation.current?.play();
}, []);

React Native how to render svg from url

I'm trying to render svg file path from #dicebear/avatars
let svg = createAvatar(style, {
seed: 'random',
// ... and other options
});
svg variable has this value =
But when i try to render in react-native is not showing even if i use a library called react-native-render-html
I'm trying to render using the library like this
<View style={styles.container}>
<HTML source={{ html: svg }} />
<StatusBar style="white" />
</View>
When i do this this is what i get[
You can do this using react-native-svg.
Steps:
Install the library using npm install react-native-svg
Rebuild the app after clearing the cache.
Now use the XML like
import React from 'react';
import {createAvatar} from '#dicebear/avatars';
import * as style from '#dicebear/avatars-identicon-sprites';
import {SvgCss} from 'react-native-svg';
const xml = createAvatar(style, {
seed: 'custom-seed',
});
export default function App() {
return <SvgCss xml={xml} width="100%" height="100%" />;
}

How to allow the props of every component to be defined in one central place in react native?

the question is clear. I think it can be done with react native elements. But how? I am very new to react native.
I read the documentation in here. It has a code like this:
import { ThemeProvider, Button } from 'react-native-elements';
const theme = {
Button: {
raised: true,
},
};
// Your App
const App = () => {
return (
<ThemeProvider theme={theme}>
<Button title="My Button" />
<Button title="My 2nd Button" />
</ThemeProvider>
);
};
What if this part of the code:
const theme = {
Button: {
raised: true,
},
};
was coded in another file. How will I make the buttons raised?
You have 2 ways to aboard your problem.
First, if you want to use the same style for your react-native-elements components across certain files and they are all the children of the same parent file, you use this bit of code :
<ThemeProvider theme={theme}>
<Button title="My Button" />
<Button title="My 2nd Button"/> // ... plus any other component that contains your react native elements components
</ThemeProvider>
for this case if you want to put your config variable in another file , you can do it like this :
create a new file that contains your config variable let say for example a new file called config.js
// config.js file
export default {
Button:{
raised:true
}
// ... other RN-elements props
}
// or this
const theme = {
Button: {
raised: true,
},
}
export {theme}
then import it in your workspace like so :
// the file were you are using your themeProvider
import theme from "path_to_your_config.js_file"
// or respectively
import {theme} from "path_to_your_config.js_file"
// then use the variable theme as you like
the second way is that you create your own custom component and you style it however you want and you use it in your app.

Unknown named Module, using component will receive props to update an image

Hi I am running into the error "Unknown named Module" when trying to dynamically update image using componentWillReceiveProps. Essentially I have a topics component which has a list of topics, when a topic is clicked it gives props to another component (thumbnails) and the images related to that topic are populated.
Here is some code for the thumbnails component:
import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, Button } from 'react-native';
import Player from './player.js';
import styles from '../stylesheet.js';
let baseurl = '../assets/thumbnails/';
let extension = '.jpeg';
export default class Thumbnails extends Component {
constructor(props){
super(props);
this.state = {
current: [
require('../assets/thumbnails/narcolepsy-1.jpeg'),
require('../assets/thumbnails/narcolepsy-2.jpeg'),
require('../assets/thumbnails/narcolepsy-3.jpeg')
]
}
}
componentWillReceiveProps(nextProps) {
setTimeout(()=>{
let topic = nextProps.current.toLowerCase();
let current = [];
for(let i = 1; i <= 3;i++){
current.push(require(baseurl + topic + '-' + i + extension));
}
this.setState({current,})
},1000)
}
render() {
const thumbnails = this.state.current.map((path,i) => {
return(<Image
source={path}
style={styles["thumbnail"+(i+1)]}
key={"thumbnail"+i} />);
})
return(
<View style={{flexDirection:'row'}}>
{thumbnails}
</View>
)
}
}
I've found a similar question (React-native image - unknown named module '../img/2.jpeg') that says to use source={uri: 'file.extension'};
and to keep image assets in the folder android/app/src/main/res/drawable
However I do not have an android folder, as I am using CRNA and Expo.io. Here is my project structure, please tell me what to do in this context:
App.js app.json my-app-key.keystore stylesheet.js
App.test.js assets node_modules yarn.lock
README.md components package.json
Using dynamic require calls is not supported by the React Native packager. This is outlined in the docs: React Native - Images
In order for this to work, the image name in require has to be known statically.
// GOOD
<Image source={require('./my-icon.png')} />
// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />
// GOOD
var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');
<Image source={icon} />
I would suggest creating a static data structure to hold your images, such as an object like:
const images = {
narcolepsy: [
require('../assets/thumbnails/narcolepsy-1.jpeg'),
require('../assets/thumbnails/narcolepsy-2.jpeg'),
require('../assets/thumbnails/narcolepsy-3.jpeg')
],
apnea: [
require('../assets/thumbnails/apnea-1.jpeg'),
require('../assets/thumbnails/apnea-2.jpeg'),
require('../assets/thumbnails/apnea-3.jpeg')
]
};
This way, the packager can load your references up when the bundle is created.

expected a component class, got [object Object]

I get an error with this code. However, changing to react-native's removes the error. Can you use div with react-native? If not, why is this error so obscure...?
var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
Text,
View,
} = ReactNative;
let Auto = React.createClass({
getInitialState: function() {
return { value: 'Ma' }
},
render: function() {
return (
<div className="fuck-react">
Blah blah blah
</div>
)
}
});
No you cannot use div tag in react-native. Since, react-native is based on JSX syntax which are automatically dispatched to native components by abstract Dom parser. you can get your answer here:https://facebook.github.io/react-native/docs/tutorial.html
Also, react-native is upadated to new version that is 0.29 , you probably should ignore old ECMA script and use new ECMA script for javascript syntax. Since, react-native uses reactjs for its javascript so better learn from here: http://reactjs.net/guides/es6.html
Instead of DIV use View.
<View style={{flex: 1}}>
<Text>Blah blah blah</Text>
</View>
You can not use in react native. Use native component instead.
<View>
<Text>text text text</Text>
</View>
Do not forget to import before with:
import {
Text,
View
} from 'react-native';
You may be using ReactJS component in a React Native App. I accidentally installed a component with <div> tags in React Native project.