RNative-Components
useState with Events in React Native
useState Hooks ? What is it ?
useState
is a React hooks that allow us to use and to modify the state in our function component(before called stateless component) without to write a class component and setState
method.
In the previous version of React before the react@16.8
, the using of state and update the state in our component was like this :
onPress() Event ::
import React,{useState} from 'react';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View,Button } from 'react-native';
export default function App() {
var [fName, sName]= useState("first text");
function abc(){
sName("second text goes here...");
}
return (
<View>
<Text style={{fontSize:30}}>{fName}</Text>
<Text style={{fontSize:30}}></Text>
<Button title='update' onPress={abc} />
</View>
);
}
onChange() Event ::
import { useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { TextInput } from 'react-native-web';
export default function App() {
var [name, setName] = useState('user');
var [age, setAge]= useState('29');
return (
<View style={styles.container}>
<Text>Enter Your Name :: </Text>
<TextInput
style={styles.input}
placeholder="enter u r name"
onChangeText={(val)=>setName(val)}
/>
<Text>Enter Age :</Text>
<TextInput
style={styles.input}
placeholder ="99"
onChangeText={(val)=>setAge(val)}
/>
<Text>name:{name}, age: {age}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
// backgroundColor: 'gray',
alignItems: 'center',
justifyContent: 'center',
},
});