I want to set the tintColor
of my png Image
dynamic. Currently I try to set the color via the state
property and change the value with setState
My code is something like this (Expect that everything works fine above and around the following code snippet):
class dynamicImageColor extends Component{
constructor(props) {
super(props);
this.state = {
myDynamicColor: '#ffffff'
}
}
changeColor(bool) {
this.setState({
myDynamicColor: bool ? '#932727' : '#ffffff';
})
}
render(){
return(
<Image source={myPNGImage} style={styles.PNGImageStyle}/>
)
}
}
var styles = StyleSheet.create({
PNGImageStyle: {
tintColor: this.state.myDynamicColor,
width: 25,
height: 25
}
}
Everything in the code above is working fine if i set the tintColor static. And the function changeColor(bool) is called in some other place which is not relevant and works fine.
My actual problem is that i get the error message:
undefined is not an object(evaluating'this.state.myDynamicColor
I also wanted to see if there are wrong values transported anyhow. But the console showed the right '#ffffff'
hex_code format at the myDynamicColor
I dont know further and help would be very nice. Also i would be glad if you show me a better solution :)
Thank you BR Jonathan
Dynamically change the view color: We can use the backgroundColor in styles to add a background color to a view. The below program does that: import React, { useState } from 'react'; import {SafeAreaView, View, StyleSheet, StatusBar, TouchableWithoutFeedback } from 'react-native'; const randomRGB = () => Math.
This is an Example to Load Different Style Sheet Dynamically on the Component in React Native. To do this we will use a conditional operator and state. When we change the state view will re-render itself and after checking the state we will change the style of the component.
To change the color of an SVG in React:Don't set the fill and stroke attributes on the SVG. Import the SVG as a component. Set the fill and stroke props on the component, e.g. <MyLogo fill="black" stroke="yellow" /> .
tintColor Changes the color of all the non-transparent pixels to the tintColor.
There are a few issues here. First your styles var can't use this
because it's not part of the class. Second the value of tintColor would not be automatically updated. render() would always use the same styles variable.
What you want to do is this (notice the square brackets):
render() {
return (
<Image source={myPNGImage} style={[styles.PNGImageStyle, {tintColor: this.state.myDynamicColor}]}/>
);
}
and
var styles = StyleSheet.create({
PNGImageStyle: {
width: 25,
height: 25
}
...
});
Pass the props to the component and use them in props of image component like below :
<Image
style={{
tintColor: props.color,
resizeMode: "contain",
height: 100,
width: 200
}}
source={require(props.imageSrc)}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With