React pass input value to parent component

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;

I’m not sure if this is the cause of your issue, but you should not be using state in both of the components. The parent’s location state should be passed down into the child component via props, and then the child component should set that as the value of the input.

2 Likes

Thanks for the reply! I tried your suggestion and it worked.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.