Hi,
I’m trying to pass the value of a text input field from a child to its parent component. The first character typed in appears as blank in the console. Only when I press another key, the first one appears. The end result is that the typed string is cut short by one character.
Hope that explanation makes sense.
Parent:
import React, {useState} from "react";
import SearchInput from "./components/SearchInput";
function App(){
const [location, setLocation] = useState("");
const getLocation = (string) => {
setLocation(string);
console.log(`location: ${location}`);
};
return(
<div>
<SearchInput onChange={getLocation} />
{location}
</div>
);
}
export default App;
Child
import {useState} from "react"
const SearchInput = ({onChange}) => {
const [text, setText] = useState("");
const search = (event) => {
setText(event.target.value);
onChange(text);
}
return (
<input
type="text"
value={text}
placeholder="Search..."
onChange={search}
/>
);
};
export default SearchInput;