I have a list of array and when I start typing in the input
list of array will filter corresponding to the value
. It works but I loose focus in the input
after typing a character.
My code:
const MyPage = (props) => {
const [searchTerm, setSearchTerm] = useState("");
const results = !searchTerm
? people
: people.filter(person =>
person.toLowerCase().includes(searchTerm.toLocaleLowerCase())
);
const handleChange = event => {
setSearchTerm(event.target.value);
};
const Desktop = ({ children }) => {
const isDesktop = useMediaQuery({ minWidth: 992 })
return (
isDesktop?
<View>
<input
type="text"
placeholder="Search"
value={searchTerm}
onChange={handleChange}
/>
<View style={{width:100, height:100, backgroundColor:'red'}}>
{results.map(item => (
<Text>{item}</Text>
))}
</View>
</View>
:null
)
}
return(
<View style={{width:'100%',justifyContent:'center'}}>
<Desktop/>
</View>
)
}
Instead of returning <Desktop/>
if I directly put
<input
type="text"
placeholder="Search"
value={searchTerm}
onChange={handleChange}
/>
<View style={{width:100, height:100, backgroundColor:'red'}}>
{results.map(item => (
<Text>{item}</Text>
))}
</View>
It will work. Any idea how to fix this issue?
Any advice or comment will be appreciated!
Thanks in advance!
it is because you are rendering the form in a function inside render(). Every time your state/prop change, the function returns a new form. it caused you to lose focus.
currentTarget. blur() within the onClick function's declaration.
Moving the Desktop
component outside of the MyApp
component fixes this issue. The major reason for this is that the Desktop
component gets recreated on each render (every time you type), which causes the input element to lose its focus. You could also somewhat mitigate this by using the useCallback
and useMemo
hooks, both described in detail in the official React documentation, but in this example they're not needed.
Also see this answer on declaring other components within a component.
Use autoFocus={true}
property of the input
Also as an hacky trick you can use autoFocus
property of your input:
<input
autoFocus={true}
type="text"
placeholder="Search"
value={searchTerm}
onChange={handleChange}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With