Search code examples
javascripthtmlreactjstags

Display the chosen value in the input field after its selecting in React


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>

Solution

  • 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>