Home > front end >  Display the chosen value in the input field after its selecting in React
Display the chosen value in the input field after its selecting in React

Time:09-30

If I chose from the live search drop-down let's say "Rice" (as described in the screenshot below) screenshot

I want that the value will be displayed in the input field after I click on "Rice", how can I do that?

Here is the input tag and the a tag that I represent the values:

<div>
                    <input type="text" placeholder="Choose food" onChange={e => setValue(e.target.value)} value={value} />
                    <div>
                        {result.map((result, index) => (
                            <a href='#' key={index}>
                                <div className='bg-warning'>
                                    {result}
                                </div>
                            </a>
                        ))}
                    </div>
                </div>

CodePudding user response:

You can set state value onClick of a tag just add onClick={e => setValue(result)} to a tag

<div>
                <input type="text" placeholder="Choose food" onChange={e => setValue(e.target.value)} value={value} />
                <div>
                    {result.map((result, index) => (
                        <a href='#' key={index} onClick={e => setValue(result)}>
                            <div className='bg-warning'>
                                {result}
                            </div>
                        </a>
                    ))}
                </div>
            </div>

CodePudding user response:

  • Have a onClick on anchor tag as below and set the state, but I would choose a different tag (not anchor) if its not used as a link

     <a href="#" key={index} onClick={()=> setValue(result)}>
       <div className="bg-warning">{result}</div>
     </a>;
    
  • Related