I'm stuck to detect if user select or typed new value.

Here I have separate datalist component:

 //DataList component

  adresses=[
  {
    "id": 1,
    "address": "address 1",
  },
  {
    "id": 2,
    "address": "address 2",
  },
  {
    "id": 3,
    "address": "address 3",
  },
  {
    "id": 4,
    "address": "address 4",
  }
]


<input
  type="text"
  list="data-list"
  className={classname}
  onChange={onchange}
  placeholder={placeholder}
/>
<datalist id="data-list">
  {adresses.map((item, idx) => {
    const { id, address } = item
    return <option key={idx} data-value={id} value={address} />
})}
</datalist>

Than I'm calling that component and passing props to it:

<DataList
  classname="event_time-inputs datasets"
  onchange={e => this.onChooseAddress(e)}
  adresses={this.state.adresses}
  placeholder={"Type or select address"}
/>

OnChange function:

 onChooseAddress(e) {
    console.log(e.target.value)
  }

if user select from options I need to somehow pass "data-value" from options. I'm new in react, please understand me for silly questions.

2 Answers

0
MOHIT KARKAR On

you can use onClick on Component. and pass idx as argument and use that later

return <option key={idx} data-value={id} value={address} onClick={() =>{this.onChooseAddress(idx)}} />

 onChooseAddress(i) {
   console.log(adresses[i].id)
   console.log(adresses[i].address)
  }
0
Martin Spd On

Or eventually you can try to assign onKeyPress event to track changes in your datalist and assign event to datalist to call your function onChooseAddress(id).