Hi Friends đź‘‹,
Welcome to Infinitbility.
To check array contains value in react native, use the includes()
method, it will return true
or false
based on array contains value or not.
As a developer, we have many times needed to check values on having array values or not.
Today, we will see how to check array contains a value or not in react native.
Let’s see, what we are going to do
- Create sample array constant
- Use
includes()
method to check username available in array or not - Show Message
Username not available
if value exists in array.
Talk is cheap, so me code.
import React, { useState } from 'react';
import { Text, View, StyleSheet, TextInput } from 'react-native';
const users = ['infintbility', 'notebility'];
export default function App() {
const [username, setUserName] = useState('');
return (
<View style={styles.container}>
<TextInput placeholder="username" style={{borderBottomWidth: 1, padding: 10}} onChange={(ev) => setUserName(ev.target.value)} />
<Text style={styles.paragraph}>{users.includes(username) ? 'Username not available' : 'Available'}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});
Output
In the above, exmple I have created the example “When username value already exists in our array then show Username not available”
Thanks for Reading…