React Native Dynamically Change View's Background Color
You can change the background color by using this.setState
Set the initial background color in your constructor
this.state = {
backgroundColor: randomHex()
}
in your render
function change your style prop to:
[styles.container, {backgroundColor: this.state.backgroundColor}]
and onClick
add
this.setState({backgroundColor: randomHex()});
Heres the full code
import React, { Component } from "react";
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
} from "react-native";
let randomHex = () => {
let letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
export default class randomBackground extends Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.state = {
backgroundColor: randomHex(),
};
}
onClick() {
console.log("clicked ");
this.setState({ backgroundColor: randomHex() });
}
render() {
return (
<TouchableHighlight
onPress={this.onClick}
style={[
styles.container,
{ backgroundColor: this.state.backgroundColor },
]}
>
<View>
<Text style={styles.instructions}>Tap to change the background</Text>
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: randomHex(),
},
instructions: {
color: "white",
},
});
AppRegistry.registerComponent("randomBackground", () => randomBackground);
change background color of View dynamically in react-native
If you want to add logic to map
, you should change it in order to return something:
{
this.state.data.variants.map((data, index) => {
var bg_color = data.option_values[1].value
return(
<TouchableOpacity style={{height: 30, width: 30, borderRadius: 15, backgroundColor: bg_color, marginHorizontal: 3}}>
</TouchableOpacity>
)
})
}
Add dynamic background color to view from state react native
Color is an array of string colors not object, you don't have to do i.color
const oem_color = this.state.color.map((color, e) => {
return (
<View
key={color}
style={{
width: 15,
height: 15,
borderRadius: 50,
backgroundColor: color,
}}
/>
);
});
React Native - Change background color in tabnavigator dynamically
what you can do is make one custom tabBar component and using javaScript immutability concept you can override style of tabBarOptions.
const MyTabnav = TabNavigator({ScreenOne: {
screen: ({ navigation, screenProps }) => <ScreenOneNav screenProps={{ tabbarNavigation: navigation, ...screenProps }} onNavigationStateChange={null} />,
navigationOptions: {
tabBarLabel: 'ScreenOne',
tabBarIcon: ({ tintColor }) => (
<View style={[styles.tabViewBox]}>
<Text style={[styles.tabText, { color: tintColor }]}>ScreenOne</Text>
</View>
)
}
},
ScreenTwo: {
screen: ({ navigation, screenProps }) => <ScreenOneNav screenProps={{ tabbarNavigation: navigation, ...screenProps, }} onNavigationStateChange={null} />,
navigationOptions: {
tabBarLabel: 'ScreenOne',
tabBarIcon: ({ tintColor }) => (
<View style={[styles.tabViewBox]}>
<Text style={[styles.tabText, { color: tintColor }]}>ScreenTwo</Text>
</View>
)
}
},
ScreenThree: {
screen: ({ navigation, screenProps }) => <StockNotificationNav screenProps={{ tabbarNavigation: navigation, ...screenProps }} onNavigationStateChange={null} />,
navigationOptions: {
tabBarLabel: 'Notifications',
tabBarIcon: ({ tintColor }) => (
<View style={[styles.tabViewBox]}>
<Text style={[styles.tabText, { color: tintColor }]}>ScreenThree</Text>
</View>
)
}
},
},
{
tabBarOptions: {
style: {
backgroundColor: white,
height: 55,
borderTopColor: 'transparent',
borderTopWidth: 1,
paddingRight: 10,
paddingLeft: 10,
borderTopWidth: 1,
borderTopColor: grayPlaceHolder
},
showLabel: false,
showIcon : true,
},
//Here Goes Your CustomTabBar Component
tabBarComponent : CustomTabBarComponent,
initialRouteName: 'ScreenTwo',
tabBarPosition: 'bottom',
animationEnabled: false,
swipeEnabled: false
}, []);
CustomTabBarComponent.js
const TabBar = (props) => {
const { navigationState } = props;
let newProps = props;
newProps = Object.assign(
{},
props,
{
style: {
// get value from redux store and set it here
backgroundColor: 'rgba(0,0,0,0.1)',
position: 'absolute',
bottom: 0,
left: 0,
right: 0
},
activeTintColor: '#fff',
inactiveTintColor: '#bbb',
},
);
return <TabBarBottom {...newProps} />;
};
Now You can connect this CustomTabBarComponent with Redux store and can change the value of whatever Property you want.
how can i change background after 1 second in react native?
You could use setTimeout()
to change the background color of the element by its className
after a specified time.
First, define a class in a CSS file with the background color you want the element to be on mount
.bg-onmount {
background-color: aquamarine;
}
Make sure you import this file (import "./App.css"
for example).
Then you declare a state variable with an initial value of the class name you defined
// a state variable for the background class
const [backgroundClass, setBackgroundClass] = useState("bg-onmount");
This state value will be bound to the className
property of the element later on.
In your useEffect()
you can set the timer with the amount of time you would want it to be that color, in your case this would be 500ms. After that time, the state value will be updated to the new className
which we set to ""
, so the background color disappears and the component re-renders.
useEffect(() => {
// set a timer
const timer = setTimeout(() => {
setBackgroundClass(""); // set class to none
}, 500);
// don't forget to clear in cleanup
return () => {
clearTimeout(timer);
};
}, []);
Don't forget to call clearTimeout()
in your cleanup function, this will stop the timer when the component unmounts.
This is how you would bind this value to your element
return (
<div className={backgroundClass}>
<p>Some text here</p>
</div>
);
Try it out in this sandbox
Dynamic color in react native
Try this:
Instead of storing the color in a global variable, you should store it in the component's state. If you don't know what state means in React, consider reading this article.
I see you call a setColor function to change the variable my
. Instead you could call
this.setState({currentColor: 'red'})
and then in a render()
method, you could append it to an array to overwrite the default style:
<SomeComponent style={[styles.myStyle, {backgroundColor: this.state.currentColor}]}/>
The point of doing this is that setState
triggers a new UI rendering.
Related Topics
React Button Onclick Redirect Page
React Router - Stay At the Same Page After Refresh
Check If a Number Has a Decimal Place/Is a Whole Number
How to Reference a JavaScript Object Property With a Hyphen in It
How to Get Checkbox Value in Angular
Using Thymeleaf Variable in Onclick Attribute
Angular 4: How to Read Content of Text File With Httpclient
How to Download a Base64-Encoded Image
Javascript Blob Filename Without Link
How to Change Data Due to Selected Value in Select Vue
Fetch - Missing Boundary in Multipart/Form-Data Post
How to Check If a Cookie Exists
How to Pass Get Request to Window.Location in JavaScript
Can We Map Over Two Arrays At Same Time in Js
Securityerror: Blocked a Frame With Origin from Accessing a Cross-Origin Frame