skip to Main Content

Here I have the state, and I am trying to pass them into child component SearchBar

App Component (parent component)

  // not related code ...

  // search
  const { search, setSearch } = useState("");

  const handleSearch = (e) => {
    setSearch(e.target.value);
  };
  
  // not related code ...

  return (
    <ContextProviders
      // not related code ...
    >
      <div className="App">
        <Navbar />
        <SearchBar search={search} handleSearch={(e) => handleSearch(e)} />
        <Outlet />
      </div>
    </ContextProviders>
  );
}

Into SearchBar when I am typing something in order to trigger setState it shows up an error:

SearchBar (child component)

import { useState } from "react";

export default function SearchBar(props) {
  // not related code ...

  console.log(props);

  return (
    <>
      <div>
        <input
          type="search"
          value={props.search}
          onChange={props.handleSearch}
          // not related code ...
        />
      </div>
    </>
  );
}

I need to get the value from the input field in the search component(child) into App component(parent), I try to pass a function which sets state into App, but it doesn’t work, I get the error:

Uncaught TypeError: setSearch is not a function at handleSearch

Does anyone see the issue here?

2

Answers


  1. why did you pass the anonymous arrow function in handleSearch? you just need to point handleSearch function. There is no need to call it.

    Login or Signup to reply.
  2. You should initialize your state as:

    const [search, setSearch] = useState("");
    

    And pass the handleSearch function like this:

    <SearchBar search={search} handleSearch={handleSearch} />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search