简体   繁体   中英

How do I search only when user press enter button?

I am learning react.
I have an input component.

<InputText
    isdisabled={false}                                      
    placeholder="Type something and press enter to search..."
    type="text"
    name="search-table"                    
    onChange={(e) => handleSearch(e)}                    
/>

I have a handleSearch function, I want to search only when user hit enter key.

  const handleSearch = (e) => {
    console.log(e.keyCode, e.keyCode, e.which); // undefined
      if (e.key === 'Enter' || e.keyCode === 13){
        // API CALL
        }
  }

But when I print console.log(e.keyCode, e.keyCode, e.which); It is returning undefined because it is now deprecated .

So how can I achieve my goal ?

<InputText
isdisabled={false}                                      
placeholder="Type something and press enter to search..."
type="text"
name="search-table"
onkeypress={(e) => handleSearch(e)}     
onChange={(e) => handleSearch(e)}>

OnKeyPress return the key what key you have entered and check condition in your function Body

const handleSearch = (e) => {

  if (e.key === 'Enter' || e.keyCode === 13){
    // API CALL
    }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM