user15076617
user15076617

Reputation:

Change input value after click on list element

I have got form with input

    <form onSubmit={handleSubmit}>
                        <input type="search"
                               onChange={handleChange}
                               onFocus={() => setFocus({name: true})}
                               onBlur={() => setFocus({name: false})}
                               value={inputName}
                        />
       </form>

and the list of elements which is rendered after this input field has focus. This input field is live searcher for elements of this rendered list.

the code to render list:

<div>
      {
           objects.map((object, index) => {
                 return (
                   <ul>
                          <li key={index}>
                                {object.name}
                          </li>
                   </ul>
                )
           })
       }
</div>

I want to make the action that when I click on the list element, the input field gets this element value. In the picture below, the input field should be Object 2 after I click on Object 2 element

enter image description here

Due to there are two independent jsx objects, I have no idea how can I do this.

Upvotes: 0

Views: 503

Answers (1)

VersifiXion
VersifiXion

Reputation: 2292

You can try to do this with a function triggered onClick on a <li> that sets the inputName value with the object.name :

<div>
<ul>
      {
           objects.map((object, index) => {
                 return (
                   
                          <li key={index} onClick={() => setInputName(object.name)}>
                                {object.name}
                          </li>
                   
                )
           })
       }
</ul>
</div>

And by the way I think your <ul> tag should be outside the map

Upvotes: 2

Related Questions