https://i.stack.imgur.com/AEGy7.png I have a TextInput component how can I write content and it suggests the next word that is highlighted as the image when i enter F and it automatically adds b.com is blacked out
CodePudding user response:
You can have a list with common keywords that you use in your app, something like this:
[
{
"id": 1,
"name": "chicken",
}
{
"id": 2,
"name": "banana",
}
]
Note that ideally you would be getting this data from an API and not manually add it yourself. Then, make a simple search bar and declare a new variable using useState:
const [filter, setFilter] = useState([])
...
<TextInput style={styles.textinput} placeholder='Search food...' onChangeText={handleChange}/>
The handleChange function is in charge of setting the new data Filter:
const handleChange = (e) => {
const currentFilter = data.filter((item) => {
return item.name.toLowerCase().includes(e.toLowerCase())
})
setFilter(currentFilter)
}
For displaying the data that you want, you can use conditional rendering. Just insert the following snippet inside the View in which you want to display your data:
{
filter.length != 0 && (
<View>
{
filter.map((item, key) => {
return <Text key={item.id} style={styles.textstyle}>{item.name}</Text>
})
}
</View>
)
}
Here is the full code:
export default function FilteringTest() {
const [filter, setFilter] = useState([])
const handleChange = (e) => {
const currentFilter = data.filter((item) => {
return item.name.toLowerCase().includes(e.toLowerCase())
})
setFilter(currentFilter)
}
return (
<View style={styles.background}>
<TextInput style={styles.textinput} placeholder='Search food...' onChangeText={handleChange} />
{
filter.length != 0 && (
<View>
{
filter.map((item, key) => {
return <Text key={item.id} style={styles.textstyle}>{item.name}</Text>
})
}
</View>
)
}
</View>
)
}
As for highlighting the values, you can simply create a new Text on top of the searchBar that contains the closest match. I suggest you read this article on filtering data in react native: https://www.freecodecamp.org/news/how-to-make-a-filter-component-in-react/
CodePudding user response:
TextInput for IOS - https://snack.expo.dev/JrWw1Zj5Z
TextInput for android - https://snack.expo.dev/piRXBQv6aM
For better view you can disable borders on TextInput or make TextInput transparent, and set borders and other styles to Text component