0% found this document useful (0 votes)
9 views31 pages

React Props, State, and Event Handling Guide

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

React Props, State, and Event Handling Guide

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

6a) write a program to work with props and states .

my-app/

├──src/

│ ├── [Link] ← Parent component

│ ├── [Link] ← Child component using props and state

│ └── [Link] ← Entry point

✅ Step-by-Step Implementation

🥇 Step 1: Set up the React App (if you haven't already)

npx create-react-app my-app

cd my-app

npm start

This will start your app at [Link]

🥈 Step 2: Create the Child Component – [Link]

Create a file: src/[Link]

import React, { useState } from 'react';

function Greeting(props) {

const [count, setCount] = useState(0); // state for button clicks

consthandleClick = () => {

setCount(count + 1); // update state on click

};

return (
<div style={{

border: '1px solid #ccc',

padding: '20px',

margin: '10px',

borderRadius: '8px'

}}>

<h2>Hello, {[Link]}!</h2> {/* using props */}

<p>You clicked the button <strong>{count}</strong> times.</p> {/* using state */}

<button onClick={handleClick}>Click Me</button>

</div>

);

export default Greeting;

🥉 Step 3: Create the Parent Component – [Link]

Edit src/[Link]:

import React from 'react';

import Greeting from './Greeting'; // import child component

function App() {

return (

<div style={{ textAlign: 'center' }}>

<h1>🌟 Props and State Demo in React</h1>

{/* Passing props to Greeting component */}

<Greeting name="Alice" />

<Greeting name="Bob" />


</div>

);

export default App;

🏁 Step 4: Entry Point – [Link]

This is usually auto-generated. Just make sure it's loading App.

import React from 'react';

import ReactDOM from 'react-dom/client';

import App from './App';

const root = [Link]([Link]('root'));

[Link](<App />);

6b) write a program to add styles(CSS &Sass Styling)and display


data.

📁 File Structure

my-styled-app/

├──src/

│ ├── [Link]

│ ├── [Link]

│ ├──[Link]← Sass styling

│ ├── [Link] ← Regular CSS styling

│ └── [Link]
🥇 Step 1: Create the App

If you haven't already:

npx create-react-app my-styled-app

cd my-styled-app

Then install Sass:

npm install sass

✅ React supports .scss files out of the box after installing sass.

🥈 Step 2: Create [Link] (component)

File: src/[Link]

import React from 'react';

import './[Link]'; // Sass style import

function UserProfile({ name, age, city }) {

return (

<div className="user-card">

<h2>{name}</h2>

<p><strong>Age:</strong> {age}</p>

<p><strong>City:</strong> {city}</p>

</div>

);

export default UserProfile;

🎨 Step 3: Sass Styling – [Link]

File: src/[Link]
$user-card-bg: #f0f0f0;

$user-card-border: #ccc;

$user-card-shadow: rgba(0, 0, 0, 0.1);

.user-card {

background-color: $user-card-bg;

border: 1px solid $user-card-border;

border-radius: 10px;

padding: 20px;

margin: 15px auto;

width: 300px;

box-shadow: 0 4px 6px $user-card-shadow;

text-align: left;

h2 {

color: #333;

p{

margin: 5px 0;

color: #555;

✅ This demonstrates how to use variables and nesting in Sass.

🥉 Step 4: Parent Component – [Link]

File: src/[Link]

import React from 'react';


import './[Link]'; // CSS styling

import UserProfile from './UserProfile';

function App() {

const users = [

{ name: 'Alice', age: 25, city: 'New York' },

{ name: 'Bob', age: 30, city: 'London' },

{ name: 'Charlie', age: 28, city: 'Paris' },

];

return (

<div className="app">

<h1>User Profile List</h1>

{[Link]((user, index) => (

<UserProfile

key={index}

name={[Link]}

age={[Link]}

city={[Link]}

/>

))}

</div>

);

export default App;

🎨 Step 5: Global CSS Styling – [Link]


File: src/[Link]

.app {

text-align: center;

font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

padding: 20px;

background-color: #fafafa;

h1 {

color: #444;

6c) write a program for responding to events.

📁 File Structure
event-demo/
├──src/
│ ├── [Link]
│ ├── [Link]
│ └── [Link] ← (Optional styling)

✅ Step-by-Step React Program for Responding to Events


🥇 Step 1: Setup (If you haven't already)
npx create-react-app event-demo
cd event-demo
npm start
🥈 Step 2: Create [Link]
File: src/[Link]
import React, { useState } from 'react';
import './[Link]';

function App() {
// State for different interactions
const [clickCount, setClickCount] = useState(0);
const [inputText, setInputText] = useState('');
const [hoverMessage, setHoverMessage] = useState('Hover over me!');

// Event handlers
consthandleButtonClick = () => {
setClickCount(clickCount + 1);
};

consthandleInputChange = (e) => {


setInputText([Link]);
};

consthandleMouseEnter = () => {
setHoverMessage('Thanks for hovering! 🐭');
};
consthandleMouseLeave = () => {
setHoverMessage('Hover over me!');
};

return (
<div className="App">
<h1>🎯 React Event Demo</h1>

{/* Click Event */}


<section>
<h2>1. Click Event</h2>
<button onClick={handleButtonClick}>Click Me!</button>
<p>You clicked {clickCount} times.</p>
</section>

{/* Input Change Event */}


<section>
<h2>2. Input Change Event</h2>
<input
type="text"
placeholder="Type something..."
onChange={handleInputChange}
/>
<p>You typed: <strong>{inputText}</strong></p>
</section>
{/* Mouse Enter/Leave Event */}
<section>
<h2>3. Mouse Events</h2>
<div
className="hover-box"
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{hoverMessage}
</div>
</section>
</div>
);
}

export default App;

🎨 Step 3: Optional Styling (CSS)


File: src/[Link]
.App {
text-align: center;
padding: 20px;
font-family: Arial, sans-serif;
}
section {
margin: 30px 0;
}

.hover-box {
background-color: #f0f0f0;
padding: 20px;
width: 200px;
margin: 0 auto;
border: 1px solid #ccc;
border-radius: 8px;
transition: background-color 0.3s;
cursor: pointer;
}

.hover-box:hover {
background-color: #e0e0e0;
}

Output in Browser
👇 Initial View:
🎯 React Event Demo

1. Click Event
[Click Me!]
You clicked 0 times.

2. Input Change Event


[Type something...]
You typed:

3. Mouse Events
Hover over me!
7a)write a program for conditional rendering .

🧱 File Structure

conditional-rendering-app/

├──src/

│ ├── [Link]

│ ├── [Link]

│ └── [Link] (optional for styling)

✅ Step-by-Step: Conditional Rendering in React

🥇 Step 1: Set up the React App

If not already done:

npx create-react-app conditional-rendering-app

cd conditional-rendering-app

npm start
🥈 Step 2: Code – [Link]

File: src/[Link]

import React, { useState } from 'react';

import './[Link]';

function App() {

const [isLoggedIn, setIsLoggedIn] = useState(false); // default: logged out

consttoggleLogin = () => {

setIsLoggedIn(!isLoggedIn);

};

// Conditional content

const message = isLoggedIn

? <h2>Welcome back, user! 🎉</h2>

: <h2>Please log in to continue.</h2>;

return (

<div className="App">

<h1>🔐 Conditional Rendering Demo</h1>

{/* Conditional message */}

{message}

{/* Toggle Button */}

<button onClick={toggleLogin}>

{isLoggedIn ? 'Log Out' : 'Log In'}

</button>
</div>

);

export default App;

🧪 Alternative: if Statement

You can also use if statements instead of ternary:

let message;

if (isLoggedIn) {

message = <h2>Welcome back!</h2>;

} else {

message = <h2>Please log in.</h2>;

🎨 Optional CSS – [Link]

.App {

text-align: center;

font-family: Arial, sans-serif;

padding: 40px;

button {

padding: 10px 20px;

font-size: 16px;

cursor: pointer;

}
7b)write a program for rendering lists.
File Structure

list-rendering-app/

├──src/

│ ├── [Link]

│ ├── [Link]

│ ├── [Link]

│ └── [Link] (optional)

🧱 Step-by-Step Implementation

🥇 Step 1: Set Up React App

npx create-react-app list-rendering-app

cd list-rendering-app

npm start

🥈 Step 2: Create a UserList Component

File: src/[Link]

import React from 'react';

import './[Link]'; // or separate CSS file

function UserList({ users }) {

return (

<div>

<h2>User List</h2>

<ul className="user-list">

{[Link]((user, index) => (

<li key={index} className="user-card">


<h3>{[Link]}</h3>

<p>Age: {[Link]}</p>

<p>Location: {[Link]}</p>

</li>

))}

</ul>

</div>

);

export default UserList;

🥉 Step 3: Use UserList in [Link]

File: src/[Link]

import React from 'react';

import UserList from './UserList';

function App() {

const users = [

{ name: 'Alice', age: 25, location: 'New York' },

{ name: 'Bob', age: 30, location: 'London' },

{ name: 'Charlie', age: 28, location: 'Paris' },

];

return (

<div className="App">

<h1>📋 React List Rendering Example</h1>

<UserList users={users} />


</div>

);

export default App;

Output in Browser

📋 React List Rendering Example

User List

[ Card ]

Alice

Age: 25

Location: New York

[ Card ]

Bob

Age: 30

Location: London

[ Card ]

Charlie

Age: 28

Location: Paris
7c)write a program for working with different form fields using react
forms

🧱 File Structure
form-fields-app/
├── src/
│ ├── [Link]
│ ├── [Link]
│ └── [Link] (optional)

✅ Step-by-Step React Form Example

🥇 Step 1: Set up the App


If you haven’t already:
npx create-react-app form-fields-app
cd form-fields-app
npm start

🥈 Step 2: Code the [Link]


File: src/[Link]
import React, { useState } from 'react';
import './[Link]';

function App() {
// Step 1: State for form fields
const [formData, setFormData] = useState({
name: '',
email: '',
age: '',
gender: '',
message: ''
});

const [submitted, setSubmitted] = useState(false);

// Step 2: Handle input changes


consthandleChange = (e) => {
const { name, value } = [Link];

setFormData((prevData) => ({
...prevData,
[name]: value
}));
};

// Step 3: Handle form submission


consthandleSubmit = (e) => {
[Link]();
setSubmitted(true);
[Link]('Form submitted:', formData);
};

return (
<div className="App">
<h1>📝 React Form Example</h1>

<form onSubmit={handleSubmit}>
<div>
<label>Name:</label><br />
<input
type="text"
name="name"
value={[Link]}
onChange={handleChange}
required
/>
</div>

<div>
<label>Email:</label><br />
<input
type="email"
name="email"
value={[Link]}
onChange={handleChange}
required
/>
</div>

<div>
<label>Age:</label><br />
<input
type="number"
name="age"
value={[Link]}
onChange={handleChange}
min="1"
required
/>
</div>

<div>
<label>Gender:</label><br />
<select
name="gender"
value={[Link]}
onChange={handleChange}
required
>
<option value="">-- Select Gender --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
</div>

<div>
<label>Message:</label><br />
<textarea
name="message"
value={[Link]}
onChange={handleChange}
rows="4"
required
></textarea>
</div>

<button type="submit">Submit</button>
</form>

{/* Step 4: Display submitted data */}


{submitted && (
<div className="submitted-data">
<h2>📋 Submitted Data:</h2>
<p><strong>Name:</strong> {[Link]}</p>
<p><strong>Email:</strong> {[Link]}</p>
<p><strong>Age:</strong> {[Link]}</p>
<p><strong>Gender:</strong> {[Link]}</p>
<p><strong>Message:</strong> {[Link]}</p>
</div>
)}
</div>
);
}

export default App;

Output in Browser
Before Submission:
📝 React Form Example

[ Name ]
[ Email ]
[ Age ]
[ Gender ▼ ]
[ Message ]
[ Submit ]
After Submission:
📋 Submitted Data:
Name: John Doe
Email: john@[Link]
Age: 28
Gender: Male
Message: Hello from React form!
9. ReactJS – Hooks, Sharing data between Components
a. Write a program to understand the importance of
using hooks.
a)1) Setup (VS Code + terminal)
1. Make sure [Link] is installed (node -v).
2. Open VS Code.
3. Create the app:

npx create-react-app hooks-demo


cd hooks-demo
code .

4. In VS Code, open the src/ folder. Replace or add files below, then run:

npm start

This opens [Link] in your browser.

2) Files to create (copy/paste)


src/[Link] — the old way (class)
import React, { Component } from "react";

class CounterClass extends Component {


constructor(props) {
super(props);
[Link] = { count: 0 };
[Link]("CounterClass: constructor");
}

componentDidMount() {
[Link]("CounterClass: componentDidMount");
[Link] = `Class clicked ${[Link]} times`;
}

componentDidUpdate(prevProps, prevState) {
if ([Link] !== [Link]) {
[Link]("CounterClass: componentDidUpdate");
[Link] = `Class clicked ${[Link]} times`;
}
}
componentWillUnmount() {
[Link]("CounterClass: componentWillUnmount");
}

render() {
return (
<div style={{ border: "1px solid #ddd", padding: 12, borderRadius:
8 }}>
<h2>Class Component (Before Hooks)</h2>
<p>You clicked <strong>{[Link]}</strong> times</p>
<button
onClick={() => [Link](prev => ({ count: [Link] +
1 }))}
style={{ padding: "8px 12px", cursor: "pointer" }}
>
Click Me (Class)
</button>
</div>
);
}
}

export default CounterClass;

src/[Link] — same behavior with Hooks


import React, { useState, useEffect } from "react";

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

// effect for updating the document title whenever `count` changes


useEffect(() => {
[Link]("CounterHook: useEffect (title) run", count);
[Link] = `Hook clicked ${count} times`;
}, [count]);

// effect that runs once on mount/unmount


useEffect(() => {
[Link]("CounterHook: mounted");
return () => [Link]("CounterHook: unmounted");
}, []);

return (
<div style={{ border: "1px solid #ddd", padding: 12, borderRadius:
8 }}>
<h2>Functional Component (With Hooks)</h2>
<p>You clicked <strong>{count}</strong> times</p>
<button
onClick={() => setCount(c => c + 1)}
style={{ padding: "8px 12px", cursor: "pointer" }}
>
Click Me (Hook)
</button>
</div>
);
}

export default CounterHook;


src/[Link] — demonstrating cleanup in useEffect
import React, { useState, useEffect } from "react";

function TimerHook() {
const [seconds, setSeconds] = useState(0);

useEffect(() => {
[Link]("TimerHook: start timer");
const id = setInterval(() => {
setSeconds(s => s + 1);
}, 1000);

// cleanup when component unmounts


return () => {
[Link]("TimerHook: clear timer");
clearInterval(id);
};
}, []);

return (
<div style={{ marginTop: 12 }}>
<h3>Timer (useEffect cleanup)</h3>
<p>Seconds since mount: {seconds}</p>
</div>
);
}

export default TimerHook;

src/[Link] — a small reusable custom hook


import { useState, useEffect } from "react";

export default function useWindowWidth() {


const isClient = typeof window === "object";
const getWidth = () => (isClient ? [Link] : 0);

const [width, setWidth] = useState(getWidth);

useEffect(() => {
if (!isClient) return;
function onResize() {
setWidth([Link]);
}
[Link]("resize", onResize);
return () => [Link]("resize", onResize);
}, [isClient]);

return width;
}

src/[Link] — uses the custom hook


import React from "react";
import useWindowWidth from "./useWindowWidth";
function WindowWidth() {
const width = useWindowWidth();
return (
<div style={{ marginTop: 12 }}>
<h3>Custom Hook: useWindowWidth</h3>
<p>Window width: {width}px (resize browser to see updates)</p>
</div>
);
}

export default WindowWidth;

src/[Link] — main app showing all components


import React from "react";
import CounterClass from "./CounterClass";
import CounterHook from "./CounterHook";
import TimerHook from "./TimerHook";
import WindowWidth from "./WindowWidth";

function App() {
return (
<div style={{ fontFamily: "system-ui, sans-serif", padding: 20 }}>
<h1>React Hooks Demo — Class vs Hooks</h1>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap:
16 }}>
<CounterClass />
<CounterHook />
</div>

<hr style={{ margin: "20px 0" }} />

<TimerHook />
<WindowWidth />
</div>
);
}

export default App;

3) Run & expected outputs


1. Start dev server:

npm start

2. In terminal you’ll see the dev server start (approx):

Compiled successfully!

You can now view hooks-demo in the browser.


Local: [Link]

3. In the browser you’ll see:


React Hooks Demo — Class vs Hooks

[Class Component (Before Hooks)]


You clicked 0 times [Click Me (Class)]

[Functional Component (With Hooks)]


You clicked 0 times [Click Me (Hook)]

Timer (useEffect cleanup)


Seconds since mount: 3 <-- increments every second

Custom Hook: useWindowWidth


Window width: 1366px

b. Write a program for sharing data between


components.

1) Setup (VS Code / Terminal)


1. Open terminal in VS Code.
2. Create app and start:

npx create-react-app share-demo


cd share-demo
code .
# In VS Code replace src/[Link] with the code below, then:
npm start

The dev server opens [Link]

2) Single-file example (paste into src/[Link])


// src/[Link]
import React, { useState, createContext, useContext } from "react";

/* ---------------------------
Approach A: Lifting state up
--------------------------- */
function LiftedParent() {
const [count, setCount] = useState(0);
[Link]("LiftedParent render", count);

return (
<section style={boxStyle}>
<h2>Lifting State Up</h2>
<ChildDisplay count={count} />
<ChildControls
onIncrement={() => setCount(c => c + 1)}
onDecrement={() => setCount(c => c - 1)}
onReset={() => setCount(0)}
/>
</section>
);
}

function ChildDisplay({ count }) {


[Link]("ChildDisplay render", count);
return <p>Count (from parent): <strong>{count}</strong></p>;
}

function ChildControls({ onIncrement, onDecrement, onReset }) {


[Link]("ChildControls render");
return (
<div style={{ display: "flex", gap: 8 }}>
<button onClick={onIncrement}>Increment (prop)</button>
<button onClick={onDecrement}>Decrement (prop)</button>
<button onClick={onReset}>Reset (prop)</button>
</div>
);
}

/* ---------------------------
Approach B: Context API
--------------------------- */
const CountContext = createContext();

function CountProvider({ children }) {


const [count, setCount] = useState(10); // different start to show
separation
[Link]("CountProvider render", count);

const increment = () => setCount(c => c + 1);


const decrement = () => setCount(c => c - 1);
const reset = () => setCount(0);

return (
<[Link] value={{ count, increment, decrement, reset }}>
{children}
</[Link]>
);
}

function ContextDisplay() {
const { count } = useContext(CountContext);
[Link]("ContextDisplay render", count);
return <p>Count (from context): <strong>{count}</strong></p>;
}

function ContextControls() {
const { increment, decrement, reset } = useContext(CountContext);
[Link]("ContextControls render");
return (
<div style={{ display: "flex", gap: 8 }}>
<button onClick={increment}>Increment (context)</button>
<button onClick={decrement}>Decrement (context)</button>
<button onClick={reset}>Reset (context)</button>
</div>
);
}

/* Demonstrate consuming context deeply (no prop drilling) */


function DeepNested() {
return (
<div style={{ border: "1px dashed #ccc", padding: 8, marginTop: 12 }}>
<h4>Deeply nested components</h4>
<LevelA />
</div>
);
}
function LevelA() { return <LevelB />; }
function LevelB() { return <LevelC />; }
function LevelC() {
// still has access to context without props
return (
<>
<ContextDisplay />
<ContextControls />
</>
);
}

/* ---------- App ---------- */


const boxStyle = { border: "1px solid #ddd", padding: 12, borderRadius: 8,
marginBottom: 12 };

export default function App() {


return (
<div style={{ padding: 20, fontFamily: "system-ui, sans-serif" }}>
<h1>Sharing Data Between Components (React Hooks)</h1>

<div style={{ display: "flex", gap: 20, alignItems: "flex-start" }}>


{/* Lifting state up example */}
<div style={{ flex: 1 }}>
<LiftedParent />
</div>

{/* Context API example */}


<div style={{ flex: 1 }}>
<section style={boxStyle}>
<h2>Context API (no prop drilling)</h2>
<CountProvider>
<ContextDisplay />
<ContextControls />
<DeepNested />
</CountProvider>
</section>
</div>
</div>
</div>
);
}

3) What you’ll see in the browser


When the app loads, the page shows two columns:

Left column — Lifting State Up

Lifting State Up
Count (from parent): 0
[Increment (prop)] [Decrement (prop)] [Reset (prop)]
Right column — Context API

Context API (no prop drilling)


Count (from context): 10
[Increment (context)] [Decrement (context)] [Reset (context)]

Deeply nested components


Count (from context): 10
[Increment (context)] [Decrement (context)] [Reset (context)]

 Note: Context example starts at 10 so you can see it's a separate shared store.

4) Example console logs (DevTools → Console)


On initial load you’ll see logs similar to:

LiftedParent render 0
ChildDisplay render 0
ChildControls render
CountProvider render 10
ContextDisplay render 10
ContextControls render
ContextDisplay render 10 // inside LevelC when deep nested renders
ContextControls render // inside LevelC

When you click Increment (prop) on the left:

LiftedParent render 1
ChildDisplay render 1
ChildControls render

Only the parent and its children re-render because the parent owns the state.

When you click Increment (context) on the right (either the top-level context controls or the
deep-nested controls):

CountProvider render 11
ContextDisplay render 11
ContextControls render
ContextDisplay render 11 // deep nested consumer re-renders too
ContextControls render // deep nested controls re-render

All consumers reading the context value update automatically — even deeply nested
components — without prop drilling.

You might also like