balloway balloway - 5 months ago 7
Javascript Question

React js Execute function on submit

I have a simple search box on my react app. The box should let the user input a phrase, and then execute another

react.js
function when they hit the enter key. I have tried every combination (put box in a form, not in a form,
onSubmit
, etc), but I can't seem to stop the page from "reloading" when the user inputs the information and presses enter.

HTML:

<input className="input" placeholder="Type it Here..." type="text" name="key" id="searchgrid" />


React JS Code:

searchForMatches(){
var value = document.getElementById("searchgrid").value;
console.log(value);
}


I just need the
searchForMatches()
function to run when the user types the enter key into the search box.

Thanks.

Answer

I hope this is what you're looking

searchForMatches(e){
        e.preventDefault() //this will stop the page from refreshing
        var value = e.target.value
        console.log(value)
    },
return(
 <div>
  <input className="input" placeholder="Type it Here..." type="text" name="key" id="searchgrid" onChange={ this.searchForMatches }/>
 </div>
)

Check the system events on React JS (https://facebook.github.io/react/docs/events.html)

Comments