Wednesday, May 27, 2020

React Native Part 3: TextInput and useState Hooks




import React, {useState} from 'react';
import { StyleSheet, Text, View, TextInput } from 'react-native';

export default function App() {
  const[name, setName] = useState('Shalvin');
  return (
    <View style={styles.container}>
      <Text>{name}</Text>
      <TextInput 
      onChangeText= { (val) => setName(val)}
      style={styles.input}></TextInput>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  input: {
    borderWidth: 1,
    borderColor: "black"
  }
});


In the above code I have declared a state called name, and initialized it's value using useState() method.

const[name, setName] = useState('Shalvin');

That name property is displayed inside a Text component. With the onChangeText of TextInput I am changing the state.

 <TextInput 
      onChangeText= { (val) => setName(val)}
      style={styles.input}></TextInput>
    </View>


No comments:

Post a Comment