React 2
React 2
- 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
-
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.
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
return (
<button onClick={toggleTheme} style={{ background: theme ===
"light" ? "#fff" : "#333", color: theme === "light" ? "#000" : "#fff" }}>
Toggle Theme
</button>
);
};
export default ThemeToggleButton;
};
};
export default ProductBlock;
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.
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.
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
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.
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
function ControlledForm() {
const [formData, setFormData] = useState({
name: "",
email: "",
subscribe: false,
gender: "",
country: "india",
age: 25,
});
return (
<form onSubmit={handleSubmit}>
{/* Text Input */}
<label>
Name:
<input type="text" name="name" value={formData.name}
onChange={handleChange} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
};
};
export default ProductBlock;
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.
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:
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.
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
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.
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
function ControlledForm() {
const [formData, setFormData] = useState({
name: "",
email: "",
subscribe: false,
gender: "",
country: "india",
age: 25,
});
return (
<form onSubmit={handleSubmit}>
{/* Text Input */}
<label>
Name:
<input type="text" name="name" value={formData.name}
onChange={handleChange} />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}