How to change image and text color when clicking using react-native?
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight
} = React;
var colors = ['#ddd', '#efefef', 'red', '#666', 'rgba(0,0,0,.1)', '#ededed'];
var backgroundcolors = ['green', 'black', 'orange', 'blue', 'purple', 'pink'];
var SampleApp = React.createClass({
getInitialState() {
return {
color: 'orange',
backgroundColor: 'rgba(0,0,0,.1)'
}
},
_changeStyle() {
var color = colors[Math.floor(Math.random()*colors.length)];
var backgroundColor = backgroundcolors[Math.floor(Math.random()*backgroundcolors.length)];
this.setState({
color: color,
backgroundColor: backgroundColor
})
},
render: function() {
return (
<View style={styles.container}>
<TouchableHighlight
onPress={ () => this._changeStyle() }
style={{ backgroundColor: this.state.backgroundColor, height: 60, flexDirection: 'row', alignItems:'center', justifyContent: 'center' }}>
<Text style={{ fontSize: 22, color: this.state.color }}>CHANGE COLOR</Text>
</TouchableHighlight>
<TouchableHighlight style={{ backgroundColor: 'red', height: 60, flexDirection: 'row', alignItems:'center', justifyContent: 'center' }}>
<Text style={{ color: 'white', fontSize:22 }} >Click Me</Text>
</TouchableHighlight>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
marginTop:60
}
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
Change color of View after user click on it
ideas: adding a value to check index of item. if index
and current
are the same, you will change the color of this item.
let [current, setCurrent] = useState(0) //add here
...
return <View>
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={dates}
renderItem={({ item, index }) => {
return (
<TouchableHighlight style={styles.bullet} onPress={() => setCurrent(index)} > {/* add here */}
<Text style=[{styles.btn}, {color: index == current ? 'red' : 'white'}]>{item.date}</Text> {/* add here */}
</TouchableHighlight>
)
}}
/>
</View>
I am coding without IDE, sorry if it has any mistakes
How to change image and background color every x seconds. React
You need to clear your interval with the return statement. That means, in every un-mount the interval will clear and when this component will mount, new interval will register. It works fine for me, hope your problem will solve also.
React.useEffect(() => {
const interval = setInterval(() => {
setValue((v) => {
return v === 4 ? 0 : v + 1;
});
}, 1000);
return () => clearInterval(interval);
}, []);
Remember, clearing any interval events is important. Otherwise it
occurs memory leak.
Here is the full example:
import React from "react";
const colors = ["#92c952", "#771796", "#24f355", "#d32776", "#f66b97"];
const images = [
"https://via.placeholder.com/150/92c952",
"https://via.placeholder.com/150/771796",
"https://via.placeholder.com/150/24f355",
"https://via.placeholder.com/150/d32776",
"https://via.placeholder.com/150/f66b97"
];
export default function App() {
const [value, setValue] = React.useState(0);
React.useEffect(() => {
const interval = setInterval(() => {
setValue((v) => {
return v === 4 ? 0 : v + 1;
});
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div className="App" style={{ backgroundColor: colors[value] }}>
<img src={images[value]} alt="img" style={{ border: "3px solid" }} />
</div>
);
}
Button Changes color when it is clicked
Try like this.
I think it can work for you.
import React, { Component } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
export default class App extends Component {
constructor() {
super();
this.state = {
counter: 0,
buttonColor: 'blue',
};
}
componentDidMount() {
setInterval(this.incrimentCounter, 100000000000);
}
incrimentCounter = () => {
this.setState({ counter: this.state.counter + 1 });
};
componentDidUpdate() {
console.log('Counter value has changed');
}
changeColor = () => {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
if(color==="#FFFFFF") return;
this.setState({
buttonColor:color
})
};
render() {
return (
<View style={{ flex: 1 }}>
<Text style={{ marginTop: 50, marginLeft: 170 }}>
{this.state.counter}
</Text>
<Button
title="Click"
style={{color:this.state.buttonColor}}
onPress={this.changeColor}></Button>
</View>
);
}
}
Well it works in here
https://snack.expo.io/AfmXSZ9R1
To Show different color to view on button click in react native
To change the color of a single view, based of a state variable, you just need to put a condition on the style prop.
For example:
<View style={{ position: 'absolute',
top: 0,
left: 20,
width: 50,
height: 50,
marginLeft:40,
backgroundColor: this.state.sum===1?"red":'#006400'}}>
<Text style={{justifyContent: 'center',flex: 1,textAlign:
'center',
marginTop:10,
color: '#ffffff',
alignItems: 'center'}}>
1
</Text>
</View>
As you have rendered them like that you have to do it on every View.
I would suggest to cycle trough a function to create a as they are all the same expect for the number.
Related Topics
Validation Using Yup to Check String or Number Length
Disable Right-Clicking in Html5 Video
How to Read Data from *.Csv File Using JavaScript
How to Change Font-Size in Vuetify Component
How to Prevent the Keyboard from Popping Up on Mobile Devices
How to Split Date and Time from the Datetime Variable in JavaScript
Javascript Innerhtml Not Updating Element
How to Match Only the Exact Word Using Indexof or Includes in JavaScript
Add Parameters to Url Without Refresh
Getting an Array of Column Names At Sheetjs
Typescript - Possible to Disable Type Checking
Run Script After Appending It to the HTML
How to Tell Chrome Web Debugger to Show the Current Mouse Position in Page Coordinates
How to Clear All Input Fields in Bootstrap Modal When Clicking Data-Dismiss Button
How to Disable Button After (Click) in Angular
Angular: Toggle Active Class on Only Button the Current Clicked Button (Not Using *Ngfor)
Sticky Header Smoothing Scroll Down
Alphanumeric, Dash and Underscore But No Spaces Regular Expression Check JavaScript