Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Unknown Prop 'onSearch'

I'm trying to use onSearch event on a search input like this:

render(){
  return(

  <input type="search" onSearch={ () => console.warn('search') }  />
  );
}

But I get the unknown prop error, any ideas of how to fix it?

I want to create a autocomplete input that fires an event when the user clicks on the "search" icon in the keyboard.

EDIT:

onSearch is not an standard attribute so I guess react wont support it. Since onSearch is the same as hitting enter key, using onKeypress will do the job:

render() {
  return (
    <main>
      <input onKeyPress={ this.onKeyPress } type="search" list="options"/>
      <datalist id="options">
        { OPTS.map(item => <option value={ item.nm } key={ item.id } data-id={ item.id } />) }
      </datalist>
    </main>
    );
  }


onKeyPress(event) {
  if (event.key === 'Enter') {
    const id = document.querySelector(`#options   option[value="${event.target.value}"]`).dataset.id;
    if (id) {
      console.warn('user search', id);
    }
  }
}
like image 843
IagoLast Avatar asked Apr 03 '17 23:04

IagoLast


1 Answers

search is absolutely a DOM event of search type input but react doesn't support it yet. so you may listen to raw dom element events.

do like this

<Input
  ref={element=>(element||{}).onsearch=this.searchHandler}
/>

this can work, you may want to know why.

First, ref attribute accept a function as a value, which will be executed with a real dom element(opposite to virtual dom).

And before the real dom be mounted to document the function will be executed too, but there's no element we can attach an event to, so we use (element||{}) to avoid errors.

Instead of using addEventListener, we use ele.onsearch way, because the component will rerender when props or state update, each time the render function be called we will attach an event to the dom element when search event fired the handler function can be run several times.

like image 58
Oboo Cheng Avatar answered Sep 17 '22 11:09

Oboo Cheng