'After implementing this auto suggestion text input in my react native app the value stored is only what was typed in not the suggestion after clicking
So I have tried to implement this code from user illusionist from another issue concerning auto filling text input with suggested text here in react native LINK: How to get suggestions while typing in text-input in react-native
this is how I implemented it >
import { Menu, TextInput } from "react-native-paper";
import React, { useState } from "react";
const Autocomplete = ({
value: origValue,
label,
data,
containerStyle,
onChange: origOnChange,
icon = 'bike',
style = {},
menuStyle = {},
right = () => {},
left = () => {},
}) => {
const [value, setValue] = useState(origValue);
const [menuVisible, setMenuVisible] = useState(false);
const [filteredData, setFilteredData] = useState([]);
const filterData = (text) => {
return data.filter(
(val) => val?.toLowerCase()?.indexOf(text?.toLowerCase()) > -1
);
};
return (
<View style={[containerStyle]}>
<TextInput
onFocus={() => {
if (value.length === 0) {
setMenuVisible(true);
}
}}
// onBlur={() => setMenuVisible(false)}
label={label}
right={right}
left={left}
style={style}
onChangeText={(text) => {
origOnChange(text);
if (text && text.length > 0) {
setFilteredData(filterData(text));
} else if (text && text.length === 0) {
setFilteredData(data);
}
setMenuVisible(true);
setValue(text);
}}
value={value}
/>
{menuVisible && filteredData && (
<View
style={{
flex: 1,
backgroundColor: 'white',
borderWidth: 2,
flexDirection: 'column',
borderColor: 'grey',
}}
>
{filteredData.map((datum, i) => (
<Menu.Item
key={i}
style={[{ width: '100%' }, menuStyle]}
icon={icon}
onPress={() => {
console.log(datum)
setValue(datum);
console.log(value)
setMenuVisible(false);
}}
title={datum}
/>
))}
</View>
)}
</View>
);
};
export default Autocomplete;
and in another page I import autocomplete and like here:
const [typZavady, setTypZavady] = useState('');
<Autocomplete
value={''}
style={[novaStyle.input]}
containerStyle={novaStyle.autocompleteContainer}
label="Typ závady"
data={['Svetla', 'Stoličky', 'Tabula', 'Projektor', 'Topenie', 'Počítače', 'Dvere', 'Iné']}
menuStyle={{backgroundColor: 'white'}}
onChange={newTyp => setTypZavady(newTyp)}
/>
However when I type and click on one of the suggested words only the part of the word I type in is stored in the const typZavady not the selected suggested word. I fiddled a bit with the code with no luck.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
