[go: up one dir, main page]

0% found this document useful (0 votes)
6 views19 pages

React 2

It is react notes on context api topic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views19 pages

React 2

It is react notes on context api topic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 19

Context API:

- This is Part of react API after 16.2 onwards. Context provides a way to pass the
data through the component tree without having to pass props
down manually at every level.
- So that if you want to avoid props drilling. You can use context API.
- Context API is the best way to avoid props drilling.
- If it is a simple application or moderate application you can use context API .
- If it is a complex application , you can go with third party libraries like mobx
or redux tool.
- Context API provides us to store global state. Instead of component state. You
can store global state.
- If it is a global state than easily you can access data at any level.
- Simply you can consume data at whichever component you need

Why do we need Context API ?


- Already we have a state, so why do we need context API?
- The state belongs to the component. The state is isolated within the
- component so the state is not accessible outside the component.
- If you want to pass that state out of the component ,You can use props
- Ex→ If we have 10 components then definitely we need props drilling. You need
to drill props manually at every level. So definitely this is not
recommended by react.

How to use Context API:


- In context API we have two important things
1. Provider
2. Consumer
- to consume the data we need provider. So in provider we need to set global
state
- To set the global state , react library is providing a method called as
createContext method

-
import { createContext } from "react";
Step1: create Context API
- First, create a new context using createContext.
import { createContext } from "react";
const ThemeContext = createContext(null); // returns an object with
properties ad provider and consumer

- By using createContext method you can create provider and you can consume
provider Data
- createContext will create an state and based on that state you can create
provider and you can create n number of providers by using createContext method
- The createContext method is coming from context API
Step 2: create a Provider by using the context you created:
- In provider use value prop, value is the default prop and by using value
you
- can set global variable in context API
- Value prop is mandatory
- The provider component wraps around the part of the application that needs
access to the context.

const ThemeProvider = ({ children }) => {


const [theme, setTheme] = useState("light");

const toggleTheme = () => {


setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
);
};

export default ThemeProvider;

useContext():
- In react 16.8 they introduced a hook called as useContext , this hook is the
alternative for Consumer
- This useContext is only available in functional component

Step 3: Use Context in a Component


- Now, access the context in a child component using useContext.
import { useContext } from "react";
import ThemeContext from "./ThemeContext";

const ThemeToggleButton = () => {


const { theme, toggleTheme } = useContext(ThemeContext);

return (
<button onClick={toggleTheme} style={{ background: theme ===
"light" ? "#fff" : "#333", color: theme === "light" ? "#000" : "#fff" }}>
Toggle Theme
</button>
);
};
export default ThemeToggleButton;

Step 4: Wrap Application with Provider


- Ensure the provider wraps the components that need access to the context.
import React from "react";
import ThemeProvider from "./ThemeProvider";
import ThemeToggleButton from "./ThemeToggleButton";
const App = () => (
<ThemeProvider>
<ThemeToggleButton />
</ThemeProvider>
);

React Conditional Rendering:


- Conditional rendering in react works the same way as conditions in javascript.
- We use conditional rendering to print content on UI based on condition.
- In react you can conditionally render jsx using js syntax like if else
condition or switch case statements, logical and operator ot ternary operator

1. First way to use conditional rendering is by using if else:


const Conditional1 = () => {
let [displayText, setDisplayText] = useState(true);
if (displayText) {
return (
<>
<h1>Welcome to Testyantra software solution pvt
ltd</h1>
<p> Lorem ipsum dolor, sit amet consectetur
adipisicing elit. Ducimus laudantium distinctio natus nulla est. Dicta modi,</p>
</>
);
} else {
return (
<>
<h1>no data found</h1>
</>
);
}
};

2. Using switch case statements


import React, { useState } from "react";
const ProductBlock = () => {
const [mode, setMode] = useState("a");
const [color, setColor] = useState("green");

if (mode === "a" && color === "red"){


return <h1 style={{ color }}>Mode is A</h1>;
}
if (mode === "b" && color === "green") return <h1
style={{ color }}>Mode is B</h1>;
if (mode === "c" && color === "yellow") return <h1
style={{ color }}>Mode is C</h1>;

};
};
export default ProductBlock;

3.conditional rendering using the ternary operator in React:


import React, { useState } from "react";
const ToggleMessage = () => {
const [isVisible, setIsVisible] = useState(true);
return (
<div>
<h1>{isVisible ? "Hello, Welcome!" : "Goodbye, See you
soon!"}</h1>
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? "Hide Message" : "Show Message"}
</button>
</div>
);
};
export default ToggleMessage;

4.Short Circuit AND Operator &&


- When you want to render either something or nothing you can use and operator,
unlike In ternary either if block executes or else block executes.
- Example:
import React, { useState } from "react";
const WelcomeMessage = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{isLoggedIn && <h1>Welcome Back, User!</h1>}
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? "Logout" : "Login"}
</button>
</div>
);
};
export default WelcomeMessage;
- The && operator ensures that the <h1> element only renders if isLoggedIn is
true.
- If isLoggedIn is false, nothing is displayed.
- Clicking the button toggles the login state.

CSS in React JS:


- In React JS, we can achieve CSS in 3 woys.
- They are
1.Inline CSS
2.Internal CSS
3.Global CSS
4.Module CSS

1. Inline CSS:
- In inline CSS, we have to use an attribute style...
- In style attribute, It accepts an object as a value.
- CSS properties should be in lower camel Cose.
- CSS properties should be written inside an expression in the form of "object".

2. Internal CSS:
- Internal CSS in React involves defining CSS rules within your component file,
but outside the JSX returned by the render method.
- It leverages JavaScript's ability to create style objects.
- You then apply these styles using the style prop on your JSX elements.
- How it works:
1.Define Style Objects: Create JavaScript objects where the keys are CSS
properties (in camelCase) and the values are the corresponding CSS values.
2.Apply Styles: Use the style prop on JSX elements. Assign the style object
you created to this prop.
- Example:
import React from 'react';

function MyComponent() {
const myStyle = {
color: 'blue',
fontSize: '20px',
backgroundColor: 'lightgray',
padding: '10px'
};

const anotherStyle = {
color: 'red',
fontWeight: 'bold'
}
return (
<div>
<h1 style={myStyle}>This is a heading with internal
styles.</h1>
<p style={anotherStyle}>This is another paragraph.</p>
<p style={{ ...myStyle, ...anotherStyle}}>This paragraph has
combined styles.</p> {/* Combining styles using spread syntax */}
</div>
);
}
export default MyComponent;

3. Global CSS:
- This CSS code will opply for the entire project.
- First, we have to create a CSS file with .css extension.
- Next, we have to import the CSS globally in the index.js or mains.jsx file

4. Module CSS:
- If we want to apply CSS for a particular set of components we have to use
Module CSS.
- First, we have to create a new file with filename.module.css Extension.
- Next, we have to import the CSS file into that particular component.
- If we want to provide any id or class name, we have to provide it with respect
to importing variable name

5. Tailwind CSS:
- Installing Tailwind CSS as a Vite.
- 1.Install Tailwind CSS
Install tailwindcss and @tailwindcss/vite via npm.
- 2.Configure the Vite plugin
- Add the @tailwindcss/vite plugin to your Vite configuration.
- In vite.config.js
import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [
tailwindcss(),
],
})
3.Import Tailwind CSS
- Add an @import to your CSS file that imports Tailwind CSS.
- In index.css
@import "tailwindcss";

React Refs:
- Ref means reference.
what is this reference? .
- See React is a frontend library so definitely you should interact with dom
- Refs provide a way to access DOM nodes or React elements created in the render
method.
- React refs is providing us to connect native DOM elements and react elements
Without having virtual DOM
- But it is recommended not to overuse react references because it is effectingour
application , because this is imperative,
without virtual DOM means it
- will not provide any optimization or performance thing.
- This is like your normal DOM.
- There are a few good use cases for refs:
● Managing focus, text selection, or media playback.
● Triggering imperative animations.
● Integrating with third-party DOM libraries.

- Because it is directly interacting with DOM elements , imperatively it is


connecting to the DOM. it is not declarative.
- But you can connect native elements through refs
useRef():
- In react 16.8 onwards they introduced one more hook called useRef.
- Either you can use createRef() or you can use useRef() .
- useRef() is only available in FBC.
- In React, the useRef hook allows you to access a DOM element directly like
document.querySelector() in plain JavaScript.
- Additionally, the useRef hook lets you modify a state without causing a re-
render.
- Here are the steps for using the useRef hook.
Step 1. Import useRef from React:

import React, { useRef } from 'react';


Step 2. Creating the ref object:
- Call the useRef() function with an initial value to create a ref
object:

const myRef = useRef(initialValue);


- The return type of the useRef() function is a mutable object MyRef.

Step 3. Attach the ref object to a DOM element.


- Attach the ref to a DOM element using the ref attribute if you want to
access the DOM element directly.

<input ref={myRef} type="text" />

Step 4. Use the ref object.


- Access the current value of the ref via the .current property inside
the event handlers.
const handleClick = () => {
console.log(myRef.current.value);
};
Step 5. Update the ref
- Update the .current property of the ref object to change its value
without causing a re-render:
myRef.current = newValue;

useRef vs. useState hook:


-The following table highlights the differences between useRef and useState hooks:

Feature useRef
useState
Purpose To persist a mutable value To
manage state in a functional component
without causing re-renders that causes
re-renders when updated.

Initial Value useRef(initialValue)


useState(initialValue)

Return Value An object with a .current property. An array


with the current state value and a function to update it.
Re-renders Does not cause re-renders when Causes re-
renders when the state is updated.
.current is updated.

Use Case Accessing DOM elements directly, Managing


component state that affects rendering.
storing mutable values, and
holding previous values.

Value Persistence Persists between renders. Persists


between renders.

Update Method Directly update .current property. Use the


setter function provided by useState

React Forms:
- We have two ways to handle forms in react js
a.Controlled way
b.Uncontrolled way

1.Uncontrolled Component:
- For uncontrolled components react doesn’t use state Thus uncontrolled
components do not depends on any state of input
elements or any event handler.
- This type of component doesn’t care about real time input changes.
- Uncontrolled components are form inputs that manage their own state internally,
rather than being controlled by React state.
- You can access the current value of the input using a ref after the form is
submitted or whenever needed
- Ref attribute is mandatory.
- Here we don’t need any handler except submit
- Uncontrolled means you cannot control by react.
- Form data is handled by the Document Object Model (DOM) rather than by React.
The DOM maintains the state of form data and updates it based on
user input.
Internal State:
- Each form element in the DOM inherently maintains its own state. For example:
- An <input> element keeps track of its value attribute internally.
- A <textarea> element holds its text content.
- A <select> element maintains the currently selected <option>.
- When a user interacts with these elements (typing in an input box, selecting an
option, etc.), the browser updates this internal state automatically.
- You can access the current value of a DOM element via JavaScript using the
element's properties (.value, .checked, etc.). In React, you typically use refs to
access these values

How to handle uncontrolled components:


- By using ref you can handle uncontrolled component , means this is not react
data flow , this id DOM data flow Means uncontrolled component managed by
components own internal state , that is DOM internal state rather than react
state .
- Uncontrolled components doesn’t have any react state. Data flow within the
component
- By using ref you can create uncontrolled component .
- These are purely imperative by using ref . Uncontrolled components are normal
low level components
- Example:
import { useRef } from "react";
const Uncontrolled = () => {
let emailRef = useRef();
let passwordRef = useRef();
let handleSubmit = e => {
e.preventDefault();
let email = emailRef.current.value;
let password = passwordRef.current.value;
console.log({ email, password });
};
return (
<div>
<section id="form">
<article>
<h2>login</h2>
<form>
<div className="form-grouop">
<label htmlFor="email">Email</label>
<input ref={emailRef} type="email"
placeholder="email" id="email"/>
</div>
<div className="form-grouop">
<label
htmlFor="password">Password</label>
<input ref={passwordRef} type="password"
placeholder="password" id="password"/>
</div>
<div className="form-grouop">
<button
onClick={handleSubmit}>Login</button>
</div>
</form>
</article>
</section>
</div>
);
};
export default Uncontrolled;

Controlled Components:
- In this approach, form data is handled by React through the use of hooks such
as the useState hook.
- In React, a controlled component is a component where form elements derive
their value from a React state.
- When a component is controlled, the value of form elements is stored in a
state, and any changes made to the value are immediately
reflected in the state.
- To create a controlled component, you need to use the value prop to set the
value of form elements and the onChange event to handle
changes made to the value.
- The value prop sets the initial value of a form element, while the onChange
event is triggered whenever the value of a form element
changes. Inside the onChange event, you need to update the state with the new
value using a state update function.

Creating controlled component:


- Initialize state object for each input you need
- Add value attribute to the input or form elements inside which we pass
respective state for updations
- State mutation(updation) add onChange event to the element

onChange:
- this is a keyboard event, anything changes in your input this event will be
triggering.
- The change event occurs when the value of an element has been changed (only
works on <input>, <textarea> and <select> elements).
- The change() method triggers the change event, or attaches a function to run
when a change event occurs.
- Note: For select menus, the change event occurs when an option is selected.4

How to get the data:


- Inside the event object we have a property called target to get our targeted
element.
Syntax - e.target
- To get the value we have to use value property on targeted element (present in
input elements only)
Syntax - e.target.value
- To get the name of our input element we have to use name property present on
targeted element (present in input element only)
Syntax - e.target.name
- Inside the onChange event update the state of that input element by getting the
value what user has entered.
To get the value use → e.target.value
- Don't add a click event on your button, instead add a submit event on your form
and then you can get your data using the state’s which you
have created for each respective element.
-Example:
import React, { useState } from "react";
// initialize state object
// add value attribute to the input of form elements and assign with
initial state
// state mutation add onChange event to the elements
const Controlled = () => {
let [email, setEmail] = useState("");
let [password, setPassword] = useState("");
let handleSubmit = e => {
e.preventDefault();
console.log({ email, password });
setEmail("");
setPassword("");
};
return (
<div>
<h2>Login</h2>
<form onSubmit={handleSubmit}>
<input type="email" placeholder="enter email"
value={email} onChange={e => { setEmail(e.target.value)}} />
<input type="password" placeholder="enter password"
value={password} onChange={e => setPassword(e.target.value)}/>
<button>Login</button>
</form>
</div>
);
};
export default Controlled;

In FBC using single function to handle change event:


- React controlled form that includes text, email, checkbox, radio, select box,
and range inputs, all managed using a single handler with useState
- Example:
import { useState } from "react";

function ControlledForm() {
const [formData, setFormData] = useState({
name: "",
email: "",
subscribe: false,
gender: "",
country: "india",
age: 25,
});

const handleChange = (event) => {


const { name, type, value, checked } = event.target;
setFormData(() => ({
...prev,
[name]: type === "checkbox" ? checked : value,
}));
};

const handleSubmit = (event) => {


event.preventDefault();
console.log("Form Data Submitted:", formData);
alert(JSON.stringify(formData, null, 2));
};

return (
<form onSubmit={handleSubmit}>
{/* Text Input */}
<label>
Name:
<input type="text" name="name" value={formData.name}
onChange={handleChange} />
</label>
<br />

{/* Email Input */}


<label>
Email:
<input type="email" name="email" value={formData.email}
onChange={handleChange} />
</label>
<br />

{/* Checkbox */}


<label>
Subscribe:
<input type="checkbox" name="subscribe" checked={formData.subscribe}
onChange={handleChange} />
</label>
<br />

{/* Radio Buttons */}


<label>Gender:</label>
<input type="radio" name="gender" value="male" checked={formData.gender ===
"male"} onChange={handleChange} /> Male
<input type="radio" name="gender" value="female" checked={formData.gender ===
"female"} onChange={handleChange} /> Female
<br />

{/* Select Dropdown */}


<label>
Country:
<select name="country" value={formData.country} onChange={handleChange}>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
</select>
</label>
<br />

{/* Range Input */}


<label>
Age: {formData.age}
<input type="range" name="age" min="18" max="60" value={formData.age}
onChange={handleChange} />
</label>
<br />

<button type="submit">Submit</button>
</form>
);
}

export default ControlledForm;

React Conditional Rendering:


- Conditional rendering in react works the same way as conditions in javascript.
- We use conditional rendering to print content on UI based on condition.
- In react you can conditionally render jsx using js syntax like if else
condition or switch case statements, logical and operator ot ternary operator

1. First way to use conditional rendering is by using if else:


const Conditional1 = () => {
let [displayText, setDisplayText] = useState(true);
if (displayText) {
return (
<>
<h1>Welcome to Testyantra software solution pvt
ltd</h1>
<p> Lorem ipsum dolor, sit amet consectetur
adipisicing elit. Ducimus laudantium distinctio natus nulla est. Dicta modi,</p>
</>
);
} else {
return (
<>
<h1>no data found</h1>
</>
);
}
};

2. Using switch case statements


import React, { useState } from "react";
const ProductBlock = () => {
const [mode, setMode] = useState("a");
const [color, setColor] = useState("green");

if (mode === "a" && color === "red"){


return <h1 style={{ color }}>Mode is A</h1>;
}
if (mode === "b" && color === "green") return <h1
style={{ color }}>Mode is B</h1>;
if (mode === "c" && color === "yellow") return <h1
style={{ color }}>Mode is C</h1>;

};
};
export default ProductBlock;

3.conditional rendering using the ternary operator in React:


import React, { useState } from "react";
const ToggleMessage = () => {
const [isVisible, setIsVisible] = useState(true);
return (
<div>
<h1>{isVisible ? "Hello, Welcome!" : "Goodbye, See you
soon!"}</h1>
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? "Hide Message" : "Show Message"}
</button>
</div>
);
};
export default ToggleMessage;

4.Short Circuit AND Operator &&


- When you want to render either something or nothing you can use and operator,
unlike In ternary either if block executes or else block executes.
- Example:
import React, { useState } from "react";
const WelcomeMessage = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{isLoggedIn && <h1>Welcome Back, User!</h1>}
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? "Logout" : "Login"}
</button>
</div>
);
};
export default WelcomeMessage;
- The && operator ensures that the <h1> element only renders if isLoggedIn is
true.
- If isLoggedIn is false, nothing is displayed.
- Clicking the button toggles the login state.

CSS in React JS:


- In React JS, we can achieve CSS in 3 woys.
- They are
1.Inline CSS
2.Internal CSS
3.Global CSS
4.Module CSS

1. Inline CSS:
- In inline CSS, we have to use an attribute style...
- In style attribute, It accepts an object as a value.
- CSS properties should be in lower camel Cose.
- CSS properties should be written inside an expression in the form of "object".

2. Internal CSS:
- Internal CSS in React involves defining CSS rules within your component file,
but outside the JSX returned by the render method.
- It leverages JavaScript's ability to create style objects.
- You then apply these styles using the style prop on your JSX elements.
- How it works:
1.Define Style Objects: Create JavaScript objects where the keys are CSS
properties (in camelCase) and the values are the corresponding CSS values.
2.Apply Styles: Use the style prop on JSX elements. Assign the style object
you created to this prop.
- Example:
import React from 'react';

function MyComponent() {
const myStyle = {
color: 'blue',
fontSize: '20px',
backgroundColor: 'lightgray',
padding: '10px'
};

const anotherStyle = {
color: 'red',
fontWeight: 'bold'
}
return (
<div>
<h1 style={myStyle}>This is a heading with internal
styles.</h1>
<p style={anotherStyle}>This is another paragraph.</p>
<p style={{ ...myStyle, ...anotherStyle}}>This paragraph has
combined styles.</p> {/* Combining styles using spread syntax */}
</div>
);
}
export default MyComponent;

3. Global CSS:
- This CSS code will opply for the entire project.
- First, we have to create a CSS file with .css extension.
- Next, we have to import the CSS globally in the index.js or mains.jsx file

4. Module CSS:
- If we want to apply CSS for a particular set of components we have to use
Module CSS.
- First, we have to create a new file with filename.module.css Extension.
- Next, we have to import the CSS file into that particular component.
- If we want to provide any id or class name, we have to provide it with respect
to importing variable name

5. Tailwind CSS:
- Installing Tailwind CSS as a Vite.
- 1.Install Tailwind CSS
Install tailwindcss and @tailwindcss/vite via npm.
- 2.Configure the Vite plugin
- Add the @tailwindcss/vite plugin to your Vite configuration.
- In vite.config.js
import { defineConfig } from 'vite'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [
tailwindcss(),
],
})
3.Import Tailwind CSS
- Add an @import to your CSS file that imports Tailwind CSS.
- In index.css
@import "tailwindcss";

React Refs:
- Ref means reference.
what is this reference? .
- See React is a frontend library so definitely you should interact with dom
- Refs provide a way to access DOM nodes or React elements created in the render
method.
- React refs is providing us to connect native DOM elements and react elements
Without having virtual DOM
- But it is recommended not to overuse react references because it is effectingour
application , because this is imperative,
without virtual DOM means it
- will not provide any optimization or performance thing.
- This is like your normal DOM.
- There are a few good use cases for refs:
● Managing focus, text selection, or media playback.
● Triggering imperative animations.
● Integrating with third-party DOM libraries.

- Because it is directly interacting with DOM elements , imperatively it is


connecting to the DOM. it is not declarative.
- But you can connect native elements through refs

useRef():
- In react 16.8 onwards they introduced one more hook called useRef.
- Either you can use createRef() or you can use useRef() .
- useRef() is only available in FBC.
- In React, the useRef hook allows you to access a DOM element directly like
document.querySelector() in plain JavaScript.
- Additionally, the useRef hook lets you modify a state without causing a re-
render.
- Here are the steps for using the useRef hook.
Step 1. Import useRef from React:

import React, { useRef } from 'react';


Step 2. Creating the ref object:
- Call the useRef() function with an initial value to create a ref
object:

const myRef = useRef(initialValue);


- The return type of the useRef() function is a mutable object MyRef.

Step 3. Attach the ref object to a DOM element.


- Attach the ref to a DOM element using the ref attribute if you want to
access the DOM element directly.

<input ref={myRef} type="text" />


Step 4. Use the ref object.
- Access the current value of the ref via the .current property inside
the event handlers.
const handleClick = () => {
console.log(myRef.current.value);
};
Step 5. Update the ref
- Update the .current property of the ref object to change its value
without causing a re-render:
myRef.current = newValue;

useRef vs. useState hook:


-The following table highlights the differences between useRef and useState hooks:

Feature useRef
useState
Purpose To persist a mutable value To
manage state in a functional component
without causing re-renders that causes
re-renders when updated.

Initial Value useRef(initialValue)


useState(initialValue)

Return Value An object with a .current property. An array


with the current state value and a function to update it.
Re-renders Does not cause re-renders when Causes re-
renders when the state is updated.
.current is updated.

Use Case Accessing DOM elements directly, Managing


component state that affects rendering.
storing mutable values, and
holding previous values.

Value Persistence Persists between renders. Persists


between renders.

Update Method Directly update .current property. Use the


setter function provided by useState

React Forms:
- We have two ways to handle forms in react js
a.Controlled way
b.Uncontrolled way

1.Uncontrolled Component:
- For uncontrolled components react doesn’t use state Thus uncontrolled
components do not depends on any state of input
elements or any event handler.
- This type of component doesn’t care about real time input changes.
- Uncontrolled components are form inputs that manage their own state internally,
rather than being controlled by React state.
- You can access the current value of the input using a ref after the form is
submitted or whenever needed
- Ref attribute is mandatory.
- Here we don’t need any handler except submit
- Uncontrolled means you cannot control by react.
- Form data is handled by the Document Object Model (DOM) rather than by React.
The DOM maintains the state of form data and updates it based on
user input.
Internal State:
- Each form element in the DOM inherently maintains its own state. For example:
- An <input> element keeps track of its value attribute internally.
- A <textarea> element holds its text content.
- A <select> element maintains the currently selected <option>.
- When a user interacts with these elements (typing in an input box, selecting an
option, etc.), the browser updates this internal state automatically.
- You can access the current value of a DOM element via JavaScript using the
element's properties (.value, .checked, etc.). In React, you typically use refs to
access these values

How to handle uncontrolled components:


- By using ref you can handle uncontrolled component , means this is not react
data flow , this id DOM data flow Means uncontrolled component managed by
components own internal state , that is DOM internal state rather than react
state .
- Uncontrolled components doesn’t have any react state. Data flow within the
component
- By using ref you can create uncontrolled component .
- These are purely imperative by using ref . Uncontrolled components are normal
low level components
- Example:
import { useRef } from "react";
const Uncontrolled = () => {
let emailRef = useRef();
let passwordRef = useRef();
let handleSubmit = e => {
e.preventDefault();
let email = emailRef.current.value;
let password = passwordRef.current.value;
console.log({ email, password });
};
return (
<div>
<section id="form">
<article>
<h2>login</h2>
<form>
<div className="form-grouop">
<label htmlFor="email">Email</label>
<input ref={emailRef} type="email"
placeholder="email" id="email"/>
</div>
<div className="form-grouop">
<label
htmlFor="password">Password</label>
<input ref={passwordRef} type="password"
placeholder="password" id="password"/>
</div>
<div className="form-grouop">
<button
onClick={handleSubmit}>Login</button>
</div>
</form>
</article>
</section>
</div>
);
};
export default Uncontrolled;

Controlled Components:
- In this approach, form data is handled by React through the use of hooks such
as the useState hook.
- In React, a controlled component is a component where form elements derive
their value from a React state.
- When a component is controlled, the value of form elements is stored in a
state, and any changes made to the value are immediately
reflected in the state.
- To create a controlled component, you need to use the value prop to set the
value of form elements and the onChange event to handle
changes made to the value.
- The value prop sets the initial value of a form element, while the onChange
event is triggered whenever the value of a form element
changes. Inside the onChange event, you need to update the state with the new
value using a state update function.

Creating controlled component:


- Initialize state object for each input you need
- Add value attribute to the input or form elements inside which we pass
respective state for updations
- State mutation(updation) add onChange event to the element

onChange:
- this is a keyboard event, anything changes in your input this event will be
triggering.
- The change event occurs when the value of an element has been changed (only
works on <input>, <textarea> and <select> elements).
- The change() method triggers the change event, or attaches a function to run
when a change event occurs.
- Note: For select menus, the change event occurs when an option is selected.4

How to get the data:


- Inside the event object we have a property called target to get our targeted
element.
Syntax - e.target
- To get the value we have to use value property on targeted element (present in
input elements only)
Syntax - e.target.value
- To get the name of our input element we have to use name property present on
targeted element (present in input element only)
Syntax - e.target.name
- Inside the onChange event update the state of that input element by getting the
value what user has entered.
To get the value use → e.target.value
- Don't add a click event on your button, instead add a submit event on your form
and then you can get your data using the state’s which you
have created for each respective element.
-Example:
import React, { useState } from "react";
// initialize state object
// add value attribute to the input of form elements and assign with
initial state
// state mutation add onChange event to the elements
const Controlled = () => {
let [email, setEmail] = useState("");
let [password, setPassword] = useState("");
let handleSubmit = e => {
e.preventDefault();
console.log({ email, password });
setEmail("");
setPassword("");
};
return (
<div>
<h2>Login</h2>
<form onSubmit={handleSubmit}>
<input type="email" placeholder="enter email"
value={email} onChange={e => { setEmail(e.target.value)}} />
<input type="password" placeholder="enter password"
value={password} onChange={e => setPassword(e.target.value)}/>
<button>Login</button>
</form>
</div>
);
};
export default Controlled;

In FBC using single function to handle change event:


- React controlled form that includes text, email, checkbox, radio, select box,
and range inputs, all managed using a single handler with useState
- Example:
import { useState } from "react";

function ControlledForm() {
const [formData, setFormData] = useState({
name: "",
email: "",
subscribe: false,
gender: "",
country: "india",
age: 25,
});

const handleChange = (event) => {


const { name, type, value, checked } = event.target;
setFormData(() => ({
...prev,
[name]: type === "checkbox" ? checked : value,
}));
};

const handleSubmit = (event) => {


event.preventDefault();
console.log("Form Data Submitted:", formData);
alert(JSON.stringify(formData, null, 2));
};

return (
<form onSubmit={handleSubmit}>
{/* Text Input */}
<label>
Name:
<input type="text" name="name" value={formData.name}
onChange={handleChange} />
</label>
<br />

{/* Email Input */}


<label>
Email:
<input type="email" name="email" value={formData.email}
onChange={handleChange} />
</label>
<br />

{/* Checkbox */}


<label>
Subscribe:
<input type="checkbox" name="subscribe" checked={formData.subscribe}
onChange={handleChange} />
</label>
<br />

{/* Radio Buttons */}


<label>Gender:</label>
<input type="radio" name="gender" value="male" checked={formData.gender ===
"male"} onChange={handleChange} /> Male
<input type="radio" name="gender" value="female" checked={formData.gender ===
"female"} onChange={handleChange} /> Female
<br />

{/* Select Dropdown */}


<label>
Country:
<select name="country" value={formData.country} onChange={handleChange}>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
</select>
</label>
<br />

{/* Range Input */}


<label>
Age: {formData.age}
<input type="range" name="age" min="18" max="60" value={formData.age}
onChange={handleChange} />
</label>
<br />

<button type="submit">Submit</button>
</form>
);
}

export default ControlledForm;

You might also like