React Event

React Event Handling

Event Handling

  • Use camel case for event handling attribute. e.g. onClick instead of onclick
  • Pass a function, don’t pass a function call

Example

1
2
3
4
5
6
7
8
9
10
function ClickButton() {
const clickHandler = (e) => {
console.log('Button Click');
}
return (
<div>
<button onClick={clickHandler}>Click</button>
</div>
)
}

You can also use in-line functions as event handler

1
2
3
4
5
6
7
8
9
function SayHello() {
const [name, setName] = useState("Bob")
return (
<>
<input type="text" defaultValue="Bob" onChange={(e) => setName(e.target.value)} />
<p>Hello, {name}</p>
</>
)
}

Passing Arguments to Event Handler

Here is an example to pass id to the function. the handle function will take parameter id and event e as parameter

1
<button onClick={(e) => handle(id, e)}>Delete</button>

if event e is not needed:

1
<button onClick={() => handle(id)}>Delete</button>

Prevent Default

To prevent the default behavior, you must call preventDefault explicitly.

1
2
3
4
5
6
7
8
9
10
11
12
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}

return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}

Reference