0% found this document useful (0 votes)
4 views

react event

React handles user events similarly to HTML, using camelCase syntax for event handlers. It allows passing arguments to event handlers through arrow functions and provides access to the React event object. To prevent default behavior, the preventDefault method must be explicitly called instead of returning false.

Uploaded by

vivekmohite104
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

react event

React handles user events similarly to HTML, using camelCase syntax for event handlers. It allows passing arguments to event handlers through arrow functions and provides access to the React event object. To prevent default behavior, the preventDefault method must be explicitly called instead of returning false.

Uploaded by

vivekmohite104
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Just like HTML DOM events, React can perform actions based on user events.

React has the same events as HTML: click, change, mouseover etc.

Adding Events
React events are written in camelCase syntax:
import React from 'react';
import ReactDOM from 'react-dom/client';

function Football() {
const shoot = () => {
alert("Great Shot!");
}

return (
<button onClick={shoot}>Take the shot!</button>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Football />);

Passing Arguments
To pass an argument to an event handler, use an arrow function.

import React from 'react';


import ReactDOM from 'react-dom/client';

function Football() {
const shoot = (a) => {
alert(a);
}

return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Football />);

React Event Object


Event handlers have access to the React event that triggered the function.

In our example the event is the "click" event.

import React from 'react';


import ReactDOM from 'react-dom/client';

function Football() {
const shoot = (a, b) => {
alert(b.type);
/*
'b' represents the React event that triggered the function.
In this case, the 'click' event
*/
}
return (
<button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Football />);

In react, we cannot return false to prevent the default behavior. We must call preventDefault event explicitly to preve

function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('You had clicked a Link.');
}
return (
<a href="#" onClick={handleClick}>
Click_Me
</a>
);
}

You might also like