0% found this document useful (0 votes)
3 views26 pages

Wdf Exercises

The document provides various examples of React components, including custom hooks for data fetching, usage of Axios for GET and PUT requests, and the implementation of presentational and container components. It also covers form handling with Formik and Yup, event handling, data binding, and testing with mock data. Additionally, it includes examples of class-based and function-based components, state management with useState, and prop validation with PropTypes.

Uploaded by

oopsitsmysteria
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)
3 views26 pages

Wdf Exercises

The document provides various examples of React components, including custom hooks for data fetching, usage of Axios for GET and PUT requests, and the implementation of presentational and container components. It also covers form handling with Formik and Yup, event handling, data binding, and testing with mock data. Additionally, it includes examples of class-based and function-based components, state management with useState, and prop validation with PropTypes.

Uploaded by

oopsitsmysteria
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
You are on page 1/ 26

CUSTOM HOOKS

import { useState, useEffect } from 'react';

function useFetch(url) {

const [data, setData] = useState(null);

const [loading, setLoading] = useState(true);

const [error, setError] = useState(null);

useEffect(() => {

fetch(url)

.then(res => {

if (!res.ok) throw new Error('Network response was not ok');

return res.json();

})

.then(json => setData(json))

.catch(err => setError(err))

.finally(() => setLoading(false));

}, [url]);

return { data, loading, error };

export default useFetch;

import React from 'react';

import useFetch from './useFetch';


function App() {

const { data: todos, loading, error } =


useFetch('https://jsonplaceholder.typicode.com/todos');

if (loading) return <p>Loading...</p>;

if (error) return <p>Error: {error.message}</p>;

return (

<div>

<h1>Todo Titles</h1>

<ul>

{todos.map(todo => (

<li key={todo.id}>{todo.title}</li>

))}

</ul>

</div>

);

export default App;

AXIOS

FOR GET

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

import axios from 'axios';


function App() {

const [todos, setTodos] = useState([]);

const [loading, setLoading] = useState(true);

const [error, setError] = useState(null);

useEffect(() => {

axios.get('https://jsonplaceholder.typicode.com/todos')

.then(response => {

setTodos(response.data);

setLoading(false);

})

.catch(err => {

setError(err);

setLoading(false);

});

}, []);

if (loading) return <p>Loading...</p>;

if (error) return <p>Error: {error.message}</p>;

return (

<div>

<h1>Todo Titles</h1>

<ul>

{todos.map(todo => (

<li key={todo.id}>{todo.title}</li>

))}

</ul>
</div>

);

export default App;

FOR PUT

import React from 'react';

import axios from 'axios';

function App() {

const handlePut = () => {

axios.put('https://jsonplaceholder.typicode.com/todos/1', {

id: 1,

title: 'Updated Todo Title',

completed: true,

userId: 1

})

.then(response => {

console.log('PUT response:', response.data);

alert('Todo updated! Check the console.');

})

.catch(error => {

console.error('Error:', error);

});

};
return (

<div>

<h1>PUT Request Example</h1>

<button onClick={handlePut}>Update Todo</button>

</div>

);

export default App;

CONTAINER AND PRESENTATIONAL COMPONENTS

CounterDisplay.js (Presentational Component)

import React from 'react';

function CounterDisplay({ count, onIncrement }) {

return (

<div>

<h1>Counter: {count}</h1>

<button onClick={onIncrement}>Increase</button>

</div>

);

export default CounterDisplay;

CounterContainer.js (Container Component)

import React, { useState } from 'react';

import CounterDisplay from './CounterDisplay';


function CounterContainer() {

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

const handleIncrement = () => {

setCount(prev => prev + 1);

};

return (

<CounterDisplay count={count} onIncrement={handleIncrement} />

);

export default CounterContainer;

App.js

import React from 'react';

import CounterContainer from './CounterContainer';

function App() {

return (

<div>

<CounterContainer />

</div>

);

}
export default App;

How to Test With Mock Data in React

Sample Component – UserCard.jsx

function UserCard({ user }) {

return (

<div>

<h2>{user.name}</h2>

<p>{user.email}</p>

</div>

);

export default UserCard;

Test File – UserCard.test.jsx

import { render, screen } from '@testing-library/react';

import UserCard from './UserCard';

// 🧪 Mock data

const mockUser = {

name: 'John Doe',

email: 'john@example.com'

};
test('renders user name and email', () => {

render(<UserCard user={mockUser} />);

// 🔍 Check if mock data appears

expect(screen.getByText('John Doe')).toBeInTheDocument();

expect(screen.getByText('john@example.com')).toBeInTheDocument();

});

REACT-NATIVE

import React from 'react';

import {Text, View} from 'react-native';

const YourApp = () =>

Return

( You can edit me ! );

};

export default YourApp;

UNIT 4

EVENT BUBBLE UP

import React from 'react';

function App() {

const handleParentClick = () => {

alert('Parent Clicked!');
};

const handleChildClick = (e) => {

alert('Child Clicked!');

// e.stopPropagation(); // Uncomment this line to stop bubbling

};

return (

<div onClick={handleParentClick} style={{ padding: 20, backgroundColor: '#eee' }}>

<button onClick={handleChildClick}>Click Me (Child)</button>

</div>

);

export default App;

HOC

withGreeting.js – HOC

import React from 'react';

function withGreeting(WrappedComponent) {

return function EnhancedComponent(props) {

return (

<div>

<p>Hello from HOC 👋</p>

<WrappedComponent {...props} />

</div>

);
};

export default withGreeting;

MyComponent.js – A Basic Component

import React from 'react';

function MyComponent() {

return <h2>I am the original component</h2>;

export default MyComponent;

App.js – Use the HOC

import React from 'react';

import MyComponent from './MyComponent';

import withGreeting from './withGreeting';

const EnhancedComponent = withGreeting(MyComponent);

function App() {

return (

<div>

<EnhancedComponent />

</div>

);

export default App;


CSS MODULES

MyComponent.module.css

.title {

color: blue;

font-size: 24px;

text-align: center;

.button {

padding: 10px 20px;

background-color: lightgreen;

border: none;

cursor: pointer;

MyComponent.js

import React from 'react';

import styles from './MyComponent.module.css'; // Import CSS module

function MyComponent() {

return (

<div>

<h1 className={styles.title}>Hello CSS Modules 👋</h1>


<button className={styles.button}>Click Me</button>

</div>

);

export default MyComponent;

App.js

import React from 'react';

import MyComponent from './MyComponent';

function App() {

return (

<div>

<MyComponent />

</div>

);

export default App;

FORMIK AND YUP

import React from 'react';

import { Formik, Form, Field, ErrorMessage } from 'formik';

import * as Yup from 'yup';


// ✅ Validation Schema

const validationSchema = Yup.object({

name: Yup.string().required('Name is required'),

email: Yup.string().email('Invalid email').required('Email is required')

});

function SimpleForm() {

return (

<Formik

initialValues={{ name: '', email: '' }}

validationSchema={validationSchema}

onSubmit={(values) => {

alert(JSON.stringify(values, null, 2));

}}

>

<Form>

<div>

<label>Name:</label>

<Field name="name" type="text" />

<ErrorMessage name="name" component="div" style={{ color: 'red' }} />

</div>

<div>

<label>Email:</label>

<Field name="email" type="email" />

<ErrorMessage name="email" component="div" style={{ color: 'red' }} />

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

</Form>

</Formik>

);

export default SimpleForm;

EVENTLISTENER

CLICK EVENT

<!DOCTYPE html>

<html>

<head>

<title>Click Event Example</title>

</head>

<body>

<button id="myButton">Click Me</button>

<script>

// Get the button element

const button = document.getElementById('myButton');

// Add click event listener

button.addEventListener('click', () => {

alert('Button was clicked!');

});

</script>
</body>

</html>

MOUSEOVER AND MOUSEIN EVENTS

<!DOCTYPE html>

<html>

<head>

<title>Mouse Events</title>

<style>

#box {

width: 200px;

height: 200px;

background-color: lightblue;

text-align: center;

line-height: 200px;

font-size: 20px;

</style>

</head>

<body>

<div id="box">Hover over me</div>

<script>

const box = document.getElementById('box');


// Mouseover event

box.addEventListener('mouseover', () => {

box.style.backgroundColor = 'lightgreen';

box.textContent = 'Mouse is over!';

});

// Mouseout event

box.addEventListener('mouseout', () => {

box.style.backgroundColor = 'lightblue';

box.textContent = 'Hover over me';

});

</script>

</body>

</html>

ONE WAY DATA BINDING

import React, { useState } from 'react';

function OneWayBindingExample() {

const [message, setMessage] = useState('Hello World!');

return (

<div>

<h1>{message}</h1> {/* Data flows from state to UI */}

<button onClick={() => setMessage('You clicked me!')}>


Change Message

</button>

</div>

);

export default OneWayBindingExample;

TWO WAY DATA BINDING

import React, { useState } from 'react';

function TwoWayBindingExample() {

const [name, setName] = useState('');

return (

<div>

<input

type="text"

value={name} // state → input field

onChange={(e) => setName(e.target.value)} // input field → state

/>

<p>Hello, {name}</p>

</div>

);

export default TwoWayBindingExample;


UNIT 3

FUNCTION BASED COMPONENTS

import React from 'react';

function Welcome() {

return (

<div>

<h1>Welcome to React!</h1>

<p>This is a function-based component.</p>

</div>

);

export default Welcome;

App.js

import React from 'react';

import Welcome from './Welcome';

function App() {

return (

<div>

<Welcome />

</div>
);

export default App;

CLASS BASED COMPONENTS

import React, { Component } from 'react';

class Welcome extends Component {

render() {

return (

<div>

<h1>Welcome to React!</h1>

<p>This is a class-based component.</p>

</div>

);

export default Welcome;

App.js

import React from 'react';

import Welcome from './Welcome';

function App() {
return (

<div>

<Welcome />

</div>

);

export default App;

SETSATE EXAMPLE

import React, { Component } from 'react';

class Counter extends Component {

constructor() {

super();

this.state = {

count: 0

};

increment = () => {

this.setState({ count: this.state.count + 1 });

};

render() {

return (

<div>
<h2>Count: {this.state.count}</h2>

<button onClick={this.increment}>Increment</button>

</div>

);

export default Counter;

USESTATE COUNTER EXAMPLE

import React, { useState } from 'react';

function Counter() {

const [count, setCount] = useState(0); // Initial value is 0

const increment = () => {

setCount(count + 1);

};

const decrement = () => {

setCount(count - 1);

};

const reset = () => {

setCount(0);

};
return (

<div>

<h2>Count: {count}</h2>

<button onClick={increment}>➕ Increment</button>

<button onClick={decrement}>➖ Decrement</button>

<button onClick={reset}>🔁 Reset</button>

</div>

);

export default Counter;

USEEFFECT EXAMPLE

import React, { useEffect } from 'react';

function HelloEffect() {

useEffect(() => {

console.log('Component mounted!');

alert('Welcome! 👋');

// Optional cleanup function

return () => {

console.log('Component will unmount!');

};

}, []); // Empty dependency array = run only once

return (

<div>
<h2>Check your console and alert 🔍</h2>

</div>

);

export default HelloEffect;

USESTATE AND USEEFFECT COUNTER EXAMPLE

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

function CounterWithEffect() {

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

// useEffect runs every time 'count' changes

useEffect(() => {

console.log(`Count updated: ${count}`);

document.title = `Count: ${count}`; // Optional: update browser tab title

}, [count]);

return (

<div>

<h2>Count: {count}</h2>

<button onClick={() => setCount(count + 1)}>➕ Increment</button>

<button onClick={() => setCount(count - 1)}>➖ Decrement</button>

</div>

);

}
export default CounterWithEffect;

PROPS EXAMPLE

APP.JS

import React from 'react';

import Greeting from './Greeting';

function App() {

return (

<div>

<Greeting name="Alice" />

<Greeting name="Bob" />

</div>

);

export default App;

GREETINGS.JS

import React from 'react';

function Greeting(props) {

return <h2>Hello, {props.name}!</h2>;

export default Greeting;


PROPTYPES EXAMPLE

GREETINGS.JS

import React from 'react';

import PropTypes from 'prop-types';

function Greeting({ name, age }) {

return (

<div>

<h2>Hello, {name}!</h2>

<p>You are {age} years old.</p>

</div>

);

// ✅ Define PropTypes

Greeting.propTypes = {

name: PropTypes.string.isRequired,

age: PropTypes.number

};

export default Greeting;

APP.JS
import React from 'react';

import Greeting from './Greeting';

function App() {

return (

<div>

<Greeting name="Alice" age={25} />

<Greeting name="Bob" />

</div>

);

export default App;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy