1

I have created a typeAhead component which is an input field with a datalist bound to it in a React app. I listen for the "onChange" event on the input field which fetches the matching typeAhead results and this works fine.

So now I am trying to add some listeners for executing the search which should happen when an option is selected from the dropdown or when "enter" key is pressed. I tried listening for the "onSelect" event but it never seems to get fired. And I'm not sure how to listen for the "enter" key event either.

render() {
        return(
            <div>
                <input  type="text" id="searchfld" list="data" placeholder="Search..." onChange={getTypeAheadResults} />

                <datalist id="data" onChange= {executesearch} onSelect={executeSearch}></datalist>
            </div>
        );
}


const getTypeAheadResults= () => {
  //fires
}

const executesearch = () => {
  //does not fire
}

any help helps, thanks!

EDIT: Tharaka Wijebandara's answer solves the "enter" key issue. still trying to figure out how to listen for datalist selection.

just to reiterate -- when the user types something in the search field, I fetch the query results and add them to the datalist. This is working fine.

What I am trying to accomplish now is to call my executeSearch function when an option is selected from the datalist.

1
  • What does datalist component is returning? It's hard to debug without knowing Commented May 26, 2017 at 14:11

2 Answers 2

2

You can listen to keyboard events: https://facebook.github.io/react/docs/events.html#keyboard-events

handleKeyPress = (e) => {
  if(e.key == 'Enter'){
    //do something here
  }
}
<input type="text" onKeyPress={this.handleKeyPress} />

But if the keypress isn't on an input, you could find a way to attach it to the body, or use react-keydown: https://www.npmjs.com/package/react-keydown which will create a global listener when your component is mounted.

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

2 Comments

datalist is not a custom component. w3schools.com/tags/tag_datalist.asp
Oh *facepalm :)
1

Use html form element instead of a div and use onSubmit event for listening "enter" key.

function render() {
  return (
    <form onSubmit={onSumbit}>
      <input
        type="text"
        id="searchfld"
        list="data"
        placeholder="Search..."
      />
      <datalist id="data"/>
    </form>
  );
}

const onSubmit = () => {
  //....
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.