0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I think the above would help. Just try to find some other property as key. Key as index is a bad practice.
yes I don't know what the object look like, if there's a property id, he can do key={object.id}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.