1

I'm trying to populate the input field with the presented searched value when there is being clicked on one of the search results.

I'm fairly new to React FC and Typescript. I'm not sure how exactly is being done. This is what I have tried with the click handler, but the click handler doesn't populate the input field with the value that is being click on.

  const [searchTerm, setSearchTerm] = React.useState<string>('');

  const [results, setResults] = React.useState<string[]>([]);


 const handleClick = () => {
setSearcTerm(searchTerm);
  };

React.useEffect(() => {}

return(

 <Input
    onChange={(event) => setSearchTerm(event.target.value)}
    value={searchTerm}
    type="search"
  />

{results.length > 0 && (
{results.map((result, index) => (
  <div key={index}>
    <div onClick={handleClick}> {result}</div>
  </div>
))}    
)
Waiz
  • 503
  • 2
  • 6
  • 15

1 Answers1

0

Currently you are not passing any input value to be set to the searchTerm.

You can do it like this:

const handleClick = (input:string) => {
  setSearcTerm(input);
};
return(

 <Input
    onChange={(event) => setSearchTerm(event.target.value)}
    value={searchTerm}
    type="search"
  />

{results.length > 0 && (
{results.map((result, index) => (
  <div key={index}>
    <div onClick={()=>handleClick(result)}> {result}</div>
  </div>
))}    
)
sakshya73
  • 5,570
  • 5
  • 22
  • 41
  • Appreciate alot! I get the type error on the handleClick = (input). the parameter input is giving error. Should it have type as 'any'? – Waiz May 07 '21 at 09:00
  • No...you should add a type...its a string add it like this : `const handleClick = (input : string) =>{}` Sorry...forgot to add type in the answer. – sakshya73 May 07 '21 at 09:03
  • Happy to help :) ...please upvote the answer if it answers your question. – sakshya73 May 07 '21 at 09:09
  • I will once I've the voting privilage. Obviously I'm not an adult yet with 13 points ;) – Waiz May 07 '21 at 09:11