Just like HTML DOM events, React can perform actions based on user events.
React has the same events as HTML: click, change, mouseover etc.
- onClick
- onChange
- onSubmit
- onMouseOver
onClick Event:
import React from "react";
function ButtonClick() {
function handleClick() {
alert("Button Clicked");
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
export default ButtonClick;Event With Use State:
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;Input Chnage Event:
import React, { useState } from "react";
function InputExample() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<input type="text" onChange={handleChange} />
<p>Your name: {name}</p>
</div>
);
}
export default InputExample;Form Submit Event:
import React from "react";
function FormExample() {
function handleSubmit(e) {
e.preventDefault();
alert("Form Submitted");
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
export default FormExample;