Inputs are everywhere! They provide interactivity in everything web.
from https://youtu.be/MKSQYsLLFEo
Even the google search bar to google "HTML inputs" is an input 😉
So how do we use HTML inputs in React?
We have seen a <button>
in action before in the Tweeter example
load = () => {
setTweets(prevTweets => prevTweets.concat(additionalTweets))
}
...
<p>
**<button onClick={load}>LOAD MORE</button>**
</p>
https://codesandbox.io/s/react-state-example-tweets-2-function-with-hooks-j5v5e
HTML inputs (and all other DOM elements) generate events in response to user actions.
This is regardless of the UI framework used, e.g:
<button>
s generate a "click" event when clicked<input>
s generate a "changed" event when we type in itevent handler - the function that handles the event
In vanilla JS, there are different ways to add an event handler to an element:
addEventListener
// adding event listener to specified button
document
.querySelector("#btn-logout")
.addEventListener("click", function() {
alert("Logging out");
});
on<Event>
// inline
<button onclick="alert('Friend added!');">Add Friend</button>
<input
placeholder="type name here..."
type="text"
onchange='document.querySelector("#text").innerHTML += " yada ";'
/>
// function call
<button onclick="chatFriend()">Chat</button>