Event handlers determine what action is to be taken whenever an event is fired. This could be a button click or a change in a text input
Handling events with React elements is similar to handling events on DOM elements, with a few minor exceptions. If you’re familiar with how events work in standard HTML and JavaScript, it should be easy for you to learn how to handle events in React
React has the same events as HTML: click, change, mouseover etc. React events are named as camelCase instead of lowercase. Likes : onClickinstead of onclick
<button onclick="test()">Take the test!</button>
<button onClick={test}>Take the test!</button>
Another difference is that, whereas you would simply return false to avoid default behavior in HTML. But in React, you must explicitly call preventDefault.
<form onsubmit="console.log('You clicked submit.'); return false">
<button type="submit">Submit</button>
</form>
function Form() {
function handleSubmit(e) {
e.preventDefault();
console.log('You clicked submit.');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
Above,e is a synthetic event. React defines these synthetic events according to the W3C spec, so you don’t need to worry about cross-browser compatibility.
import React from 'react';
import ReactDOM from 'react-dom';
function Examination() {
const test = () => {
alert("Test Exam taken Successfully!");
}
return (
<button onClick={test}>Take the test!</button>
);
}
ReactDOM.render(<Examination />, document.getElementById('root'));
You can handle events in class components by binding them with the fat arrow function.
an arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.
"Exam" as e parameter in test function, to using arrow function
import React from 'react';
import ReactDOM from 'react-dom';
function Examination() {
const test = (e) => {
alert(e);
}
return (
<button onClick={() => test("Exam!")}>Take the test!</button>
);
}
ReactDOM.render(<Examination />, document.getElementById('root'));
to learn more about Conditional Rendering go to next chapter.