Why I get the error trying to lift up props?

Advertisements

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: 
**ERROR**

Uncaught TypeError: setSearch is not a function
at handleSearch

Does anyone see the issue here?

>Solution :

You should initialize your state as:

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

And pass the handleSearch function like this:

<SearchBar search={search} handleSearch={handleSearch} />

Leave a ReplyCancel reply