State is another way apart from props by which we can modify a React component. React component’s state value changes in the life cycle of component, unlike props. We should not directly change state value of react component. React framework gives the setState method by which state of a component should be changed.

import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
class Counter extends React.Component {
state = { count: 0 };
increment = () => this.setState({count: this.state.count + 1});
decrement = () => this.setState({count: this.state.count - 1});
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.decrement}>
<Text style={styles.text}>-</Text>
</TouchableOpacity>
<Text style={styles.text}>{this.state.count}</Text>
<TouchableOpacity onPress={this.increment}>
<Text style={styles.text}>+</Text>
</TouchableOpacity>
</View>
);
}
};
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
borderRadius: 5,
borderWidth: 1,
borderColor: '#1a91b8',
padding: 5,
backgroundColor: '#eaf7fd'
},
text: {
color: '#015169',
fontWeight: 'bold',
fontSize: 20,
padding: 15
}
});
export default Counter;
Above code is an implementation of a counter component. This component has a state count whose value is changed by clicking on the plus (+) and minus (-) button. As the state count of this component is changing the number displayed on UI is also changing. Whenever we create any component in React, first we divide the screen in the component then decide what state a component should have. The beauty of this component is that it is an independent component and can be used anywhere in the application. That is how we make several fully functional component in React to build the complete application.
Leave a Reply