0% found this document useful (0 votes)
8 views45 pages

ReactJS Event Handling Guide

The document provides an overview of ReactJS components, focusing on event handling, conditional rendering, and hooks. It explains the principles of React events, including the use of synthetic events and the event object, as well as various methods for conditional rendering. Additionally, it introduces React hooks, specifically the useState and useEffect hooks, which allow functional components to manage state and side effects without converting to class components.

Uploaded by

vikas20012005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views45 pages

ReactJS Event Handling Guide

The document provides an overview of ReactJS components, focusing on event handling, conditional rendering, and hooks. It explains the principles of React events, including the use of synthetic events and the event object, as well as various methods for conditional rendering. Additionally, it introduces React hooks, specifically the useState and useEffect hooks, which allow functional components to manage state and side effects without converting to class components.

Uploaded by

vikas20012005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

REACTJS

COMPONENT
API
PROF. VIDYA A
HOD, CS DEPARTMENT
SURANA COLLEGE-AUTONOMOUS
CONTENTS
FORMS

EVENTS

LISTS

HOOKS

CONDITIONAL RENDERING

CSS WITH REACT

ROUTERS

REF AND KEYS

CONTEXT

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 2


REACT EVENTS
PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS
EVENTS
React lets you add event handlers to your JSX.

Event handlers are your own functions that will be triggered in response to interactions like
clicking, hovering, focusing form inputs, and so on.
Event declaration in react is different from HTML, React uses:
✓ the camelCase convention instead of lowercase letters.
✓ JSX is used in react instead of plain html.
React has its own event handling system which is very similar to handling events on DOM
elements. The react event handling system is known as Synthetic Events. The synthetic
event is a cross-browser wrapper of the browser's native event.

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 4


React and HTML events
Event in HTML Event in React

<button onclick="showMessage()"> <button onClick={showMessage}>


Hello React Programing Hello React Programming
</button> </button>

A function is passed as the event


handler instead of a string.

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 5


React Events
React Event Description

onClick This event is used to detect mouse click in the user interface.

onChange This event is used to detect a change in input field in the user interface.

This event fires on submission of a form in the user interface and is also used
onSubmit
to prevent the default behavior of the form.

onKeyDown This event occurs when user press any key from keyboard.

onKeyUp This event occurs when user releases any key from keyboard.

onMouseEnter This event occours when mouse enters the boundary of the element

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 6


Basic Principles of Event Handling in React

Event handling in React is Synthetic event system


guided by a few basic
principles that align with its Naming conventions
component-based
architecture. Passing event handlers as props
These principles include:
Inline function and component methods

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 7


Basic Principles of Event Handling in React

Synthetic ensures events behave consistently across different browsers. This wraps the native
event system in browsers, providing a unified API regardless of the browser in
Event System which React is run.

Naming revolve around a set of consistent naming. Every event uses a camelCase naming
convention, and the handler function they run is prefixed with "handle", followed
conventions by the event name. For example, an onClick event running a handleClick function.

Event are the functions that run when the event is fired. They're usually defined before
the render, just above the return statement. On many occasions, they are also
handlers passed as props to components.

Inline events typically run inline functions or standalone functions within the component
when fired. With this, you can utilize hooks like useState for state and useCallback
functions for memoizing handler functions.

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 8


Adding React Events
React events syntax is in camelCase, not lowercase.

Creating an event in React starts with attaching the event name to the element that will fire it,
with the handler function referenced in it:

React Events Syntax:

onEvent_name={function}

Example:

<button onClick={handleClick}>

Click me

</button>

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 9


To define an Event Handler
An event handler function is a function that will run when the event is triggered:

const handleClick = () => {

alert('You clicked me');

};

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 10


Program to demonstrate Events
const Counter = () => {
const handleClick = () => { Event handler (handleClick)
alert('You clicked me!'); defined in the component
};
return (
<div >
<button
onClick={handleClick}> Firing the click event on the button element
Click me
</button>
</div>
);
};
export default Counter;

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 11


REACT EVENTS OBJECT

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS


React Event Object
React Events handlers have an object called Events, which contains all the details about the
event, like type, value, target, ID, etc. So, we can pass that event as an argument and use that
event object in our function.

The Event object is a wrapper around the native DOM event, providing consistent behavior
across different browsers.

React's event system is implemented as Synthetic Events, which are lightweight, cross-browser
wrappers around the browser's native events.

React Event Object Syntax:

onClick={(event)=>{function(event)}}

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 13


Key Features of the React Event Object

Cross-browser Compatibility:
• React normalizes event behavior to make it consistent across browsers.

Synthetic Event:
• The event object wraps the native DOM event and mimics its behavior.

Supports All DOM Events:


• The React event object supports all the same types of events as the
DOM, such as click, keypress, and submit.

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 14


Common Properties of the Event Object

Property/Method Description

[Link] Type of the event (e.g., click, keydown).

[Link] The DOM element that triggered the event.

[Link] The DOM element where the event handler is attached.

[Link]() Prevents the default action associated with the event.

[Link]() Stops the event from propagating to parent elements.

[Link] Accesses the original browser event

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 15


Program to demonstrate event object

//Program to demonstrate Properties of event object


function App() {
const handleClick = (event) => {
[Link]('Event type:', [Link]); // event type (e.g., "click")
[Link]('Button clicked:', [Link]); // Logs the clicked button
};
return ( <button onClick={handleClick}>Click Me</button> );
}
export default App;

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 16


Program to demonstrate event object

//Program to demonstrate use of onChange event of a textbox

function App() {

const handleChange = (event) => {

[Link]('Input value:', [Link]);

};

return <input type="text" onChange={handleChange} />;}

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 17


CONDITIONAL RENDERING
PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS
What is conditional rendering?
In React, we can render components depending on some conditions or the state of our
application.

In other words, based on one or several conditions, a component decides which elements it
will return.

In React, conditional rendering works the same way as the conditions work in JavaScript.

We use JavaScript operators to create elements representing the current state, and then
React Component update the UI to match them.

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 19


Benefits of conditional rendering
Improved User Experience
• allows you to create dynamic user interfaces that adapt to changes in data and user interactions

Improved Performance
• By conditionally rendering content, you can avoid rendering unnecessary components and improve
the performance of your application
Simplified Code
• By using conditional statements to decide what content should be rendered, you can avoid
duplicating code and create more modular components
Flexibility
• By rendering different content based on the application state, you can create components that can
be used in different contexts and adapt to different user interactions.

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 20


Types of conditional rendering

if

ternary operator

logical && operator

switch case operator


PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 21
If condition
It is the easiest way to have a conditional rendering in function UserLogin(props) {
return <h1>Welcome!</h1>;
React in the render method. }
function GuestLogin(props) {
It is restricted to the total block of the component. return <h1>Please sign up.</h1>;
}
IF the condition is true, it will return the element to be function SignUp(props) {
const isUserLogin = [Link];
rendered. if (isUserLogin) {
return <User Login />;
Syntax: }
return <Guest Login />;
if(condition) { }
[Link](
//element to be rendered <SignUp isUserLogin={false} />,
[Link]('root')
} );

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 22


Logical && operator
This operator is used for checking the
function Greeting(props) {
condition. If the condition is true, it will
const isLoggedIn = [Link];
return the element right after &&, and if it
return (
is false, React will ignore and skip it. <div> {
{ isLoggedIn && <h1>Welcome back!</h1>
condition && }
// whatever written after && </div> );
//will be a part of output. }
}

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 23


Ternary operator
The ternary operator is used in cases where two
blocks alternate given a certain condition. This render() {
operator makes your if-else statement more const isLoggedIn = [Link];
concise. It takes three operands and used as a return (
shortcut for the if statement. <div>
Welcome {isLoggedIn ? 'Back' : 'Please login first'}.
Syntax
</div>
condition ? true : false );

If the condition is true, statement1 will be }

rendered. Otherwise, false will be rendered.

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 24


Switch case operator
Sometimes it is possible to have function NotificationMsg({ text}) {
multiple conditional renderings. switch(text) {

In the switch case, conditional case 'Hi All':


return <Message: text={text} />;
rendering is applied based on a
case 'Hello Surana':
different state.
return <Message text={text} />;
default:
return null;
}
}

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 25


REACT
HOOKS

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS


What is a hook?
Hooks are a new addition in React 16.8. They let you use state and other React features without
writing a class.

Hooks in React allow the functional components to use states and manage side effects. They
let developers to hook into the state and other React features without having to write a class.

They provide a cleaner and more concise way to handle state and side effects in React
applications.

If you write a function component, and then you want to add some state to it, previously you do this
by converting it to a class. But now you can do it by using a Hook inside the existing function
component.

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 27


Rules of hooks
Hooks are similar to JavaScript functions, but you need to follow these two rules when using
them. Hooks rule ensures that all the stateful logic in a component is visible in its source code.
These rules are:
1. Only call Hooks at the top level
Do not call Hooks inside loops, conditions, or nested functions. Hooks should always be used at
the top level of the React functions. This rule ensures that Hooks are called in the same order
each time a components renders.
2. Only call Hooks from React functions
You cannot call Hooks from regular JavaScript functions. Instead, you can call Hooks from React
function components. Hooks can also be called from custom Hooks.

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 28


Types of hooks

State hook

Context hook

Effect hook

Ref hook

Performance hook

Custom hook

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 29


State hook – useState() hook
The 'useState' hook allows functional components to declare and manage state.
It returns an array with the current state value and a function to update that state.
To import the useState hook, write the following code at the top level of your component
import { useState } from "react";
This hook takes some initial state and returns two value. The first value contains the state and the second
value is a function that updates the state. The value passed in useState will be treated as the default value.
Syntax:
const [var, setVar] = useState(initialValue);
Here, var: name of the state variable
setVar: function to manage and modify the state variable
initialValue: the first value to initialize the variable

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 30


Program to demonstrate useState
import React, { useState } from 'react';

function CountApp() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default CountApp;

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 31


Effect hook – useEffect hook
React useEffect hook handles the effects of the dependency array. (The dependency array is an array of
variables that the hook depends on. React monitors these variables and runs the hook logic again only when one of
them changes)

The useEffect Hook allows us to perform side effects on the components such as fetching data, directly updating
the DOM and timers are some side effects. It is called every time any state if the dependency array is modified or
updated.

Syntax:

useEffect(<FUNCTION>, <DEPENDECY>)

where

FUNCTION: contains the code to be executed when useEffect triggers.

DEPENDENCY: is an optional parameter, useEffect triggers when the given dependency is changed.

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 32


Program to demonstrate useEffect
// useEffect is defined here

import { useState, useEffect } from "react";

function HookCounterOne() {
const [count, setCount] = useState(0);

useEffect(() => {
[Link] = `You clicked ${count} times`;
}, [count]);

return (
<div>
<button onClick={() => setCount((prevCount) => prevCount + 1)}>
Click {count} times{" "}
</button>
</div>
);
}
export default HookCounterOne;

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 33


Styling in
React

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS


CSS styling in React
Inline styling

To style an element with the inline style attribute, the value must be a JavaScript object:

CSS stylesheets

You can write your CSS styling in a separate file, just save the file with the .css file
extension, and import it in your application.

CSS Modules

The CSS inside a module is available only for the component that imported it, and you do
not have to worry about name conflicts.
Create the CSS module with the .[Link] extension, example: [Link].

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 35


Inline CSS
You write CSS directly inside the JSX element using the
function App() {
style attribute. return (
In React, inline styles are written as JavaScript objects, <h1 style={{ color: "green", fontSize: "30px" }}>
Inline Style Example
not strings. </h1>
);
In JSX, JavaScript expressions are written inside
}
curly braces, and since JavaScript objects also use
export default App;
curly braces, the styling in the example above is
written inside two sets of curly braces {{}}. The outer Note: property names use camelCase (e.g.,
box tells React: “I’m using JavaScript.” The inner box fontSize, backgroundColor).
holds the style information.
Syntax
style={{ propertyName: "value" }}
PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 36
External CSS
You create a separate .css file and import [Link]
it into your component. This keeps
import './[Link]';
structure and styling separate and clean.
function App() {
Syntax
return (
import './[Link]'; <div className="title">Welcome to React</div>
);
}
[Link]
export default App;
.title {
color: blue;
font-size: 24px;
text-align: center;
}

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 37


Modules CSS - for unique component-level styles

[Link]
CSS modules avoid style conflicts by generating unique
.box {
class names automatically. padding: 20px;
background-color: lightyellow;
File name must end with .[Link]. border: 1px solid #ccc;
}
The CSS inside a module is available only for the
[Link]
component that imported it, and you do not have to import styles from './[Link]';
worry about name conflicts.
function Card() {
Syntax: return (
<div className={[Link]}>
import styles from './[Link]’; This is a card component.
</div>
How to use? );
}
className={[Link]}
export default Card;

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 38


Lists in
React

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS


Lists in React
Lists are used to display collections of data, such as user profiles, product catalogs, or
task lists, and are commonly rendered using the JavaScript map() function to transform
arrays into JSX elements.

Why do we use map() for lists?


• In JSX, you cannot directly print an array of objects or elements.
So, we use the .map() method to loop through the array and return JSX for each item.
• The map() method iterates over an array and returns a new array of JSX elements,
which can then be rendered within a container element like <ul> or <div>.
• For example, an array of fruit names can be rendered as a list of <li> elements using
[Link]((item) => <li key={item}>{item}</li>).

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 40


map() Method
map() is a JavaScript method used to:
➢ Loop through an array
➢ Process each item
➢ Return a new value for each item
➢ React uses it to generate elements for each item in a list.
Syntax:
[Link]((item, index) => {
return something;
});
where,
item → current element
index → item position (optional)
Always return JSX when using map inside React.

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 41


map() Method Example
function App() { • [Link](...) loops over each name
const students = ["Arun", "Meera", "Kiran"];
• For every name, a <li> (list item) is returned
• key={index} is required so React can track each item
return (
<div> uniquely
<h2>Student List</h2> Why is the key attribute important?
<ul>
React needs a unique key to identify each list item
{[Link]((name, index) => (
and update it efficiently.
<li key={index}>{name}</li>
Keys allow React to keep track of elements. This way,
))}
if an item is updated or removed, only that item will
</ul>
be re-rendered instead of the entire list.
</div>
Key Rules
);
} Should be unique
export default App; Can use index for simple lists

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 42


Program to demonstrate List of Objects
function App() {
const products = [
{ id: 1, name: "Laptop", price: 50000 },
{ id: 2, name: "Mouse", price: 500 },
{ id: 3, name: "Keyboard", price: 1000 }
];

return (
<div>
<h2>Product List</h2>
<ul>
{[Link]((item) => (
<li key={[Link]}>
{[Link]} - ₹{[Link]}
</li>
))}
</ul>
</div>
);
}
export default App;

PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS 43


PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS
PROF. VIDYA A, HOD, CS DEPT, SURANA COLLEGE-AUTONOMOUS

You might also like