React JS1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

React JS

29 December 2023 22:54

Q. Proms In React Js ?
1. React components use props to communicate with each other.
2. Every parent component can pass some information to its child components by giving them props.
3. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, and functions.
4. Familiar props
Props are the information that you pass to a JSX tag. For example, className, src, alt, width, and height are some of the pro ps you can pass to an <img>:

Step 1: Pass props to the child component


First, pass some props to Avatar. For example, let’s pass two props: person (an object), and size (a number):

exportdefaultfunctionProfile(){
return(
<Avatar
person={{name:'Lin Lanying',imageId:'1bX5QH6'}}
size={100}
/>
);
}

If double curly braces after person= confuse you, recall they’re merely an object inside the JSX curlies.
Now you can read these props inside the Avatar component.

Step 2: Read props inside the child component


You can read these props by listing their names person, size separated by the commas inside ({ and }) directly after function Avatar. This lets you use
them inside the Avatar code, like you would with a variable.

function Avatar({ person, size }) {


// person and size are available here
}

functionAvatar(props){
letperson= props.person;
letsize= props.size;
// ...
}

Props let you think about parent and child components independently. For example, you can change the person or the size props inside Profile without
having to think about how Avatar uses them. Similarly, you can change how the Avatar uses these props, without looking at the Profile.

You can think of props like “knobs” that you can adjust. They serve the same role as arguments serve for functions —in fact, props are the only argument to
your component! React component functions accept a single argument, a props object:

Usually you don’t need the whole props object itself, so you destructure it into individual props.

Don’t miss the pair of { and } curlies inside of ( and ) when declaring props:

function Avatar({ person, size }) {


// ...
}
This syntax is called “destructuring” and is equivalent to reading properties from a function parameter:

function Avatar(props) {
let person = props.person;
let size = props.size;
// ...
}

Specifying a default value for a prop


If you want to give a prop a default value to fall back on when no value is specified, you can do it with the destructuring b y putting = and the default value
right after the parameter:

function Avatar({ person, size = 100 }) {


// ...
}
Now, if <Avatar person={...} /> is rendered with no size prop, the size will be set to 100.

The default value is only used if the size prop is missing or if you pass size={undefined}. But if you pass size={null} or size={0}, the default value will not be
used.

Q .How props change over time


The Clock component below receives two props from its parent component: color and time.
export default function Clock({ color, time }) {

New Section 1 Page 1


export default function Clock({ color, time }) {
return (
<h1 style={{ color: color }}>
{time}
</h1>
);
}

Pick a color: dropdown

12:13:44 AM
This example illustrates that a component may receive different props over time. Props are not always static! Here, the time prop changes every second,
and the color prop changes when you select another color. Props reflect a component’s data at any point in time, rather than only in the be ginning.

Q> Conditional Rendering In React.JS

Conditional rendering in React involves rendering different content or components based on certain conditions.

import React, { useState } from "react";


function GreetingComponent(){
const[isDarkMode,setIsDarkMode]=useState(false);
const toggleTheme =()=>{
setIsDarkMode(!isDarkMode)
}
return(
<div style={{backgroundColor :isDarkMode ? '#333' : '#fff' ,color:isDarkMode ?'#fff':'#333' }}>
<h1>{isDarkMode ? 'Good Evening' :'Good Morning '},User!</h1>
<button onClick={toggleTheme}>
Switch to {isDarkMode ? 'Light' : 'Dark'} Mode
</button>
</div>
)
}
export default GreetingComponent

In React, there are several ways to implement conditional rendering. The choice of method depends on the complexity of the
conditions and personal preferences. Here are some common approaches:

1. Inline If with Logical && Operator:


• Use the logical && operator to conditionally render content.
{isLoggedIn && <p>Welcome, User!</p>}

2. Ternary Operator:
• Use the ternary operator for simple conditions.
{isLoggedIn ? <p>Welcome, User!</p>: <p>Please log in.</p>}

3. If-Else Statements Outside JSX:


• Use regular JavaScript if-else statements to conditionally render JSX outside the JSX block.
let greeting;
if (isLoggedIn) {
greeting = <p>Welcome, User!</p>;
} else {
greeting = <p>Please log in.</p>;
}
// Inside render return
{greeting}

4. Switch Statements:
• Use switch statements for multiple conditions
switch (userRole) {
case 'admin':
return <p>Welcome, Admin!</p>;
case 'user':
return <p>Welcome, User!</p>;
default:
return <p>Please log in.</p>;
}

5. Map and Filter:


• Use map and filter to conditionally render based on an array or list.
{items.map(item => (
item.isDisplayed && <ItemComponent key={item.id} data={item} />

New Section 1 Page 2


item.isDisplayed && <ItemComponent key={item.id} data={item} />
))}

6. Logical OR Operator:
• Use the logical || operator to provide a default value when a condition is false.
{userRole === 'admin'|| <p>Welcome, User!</p>}

7. Render Props:
• Use a function as a child (render prop) to conditionally render content.
<ConditionalRenderrender={() =><p>Welcome, User!</p>} />

8. Higher-Order Components (HOCs):

• Use HOCs to wrap components based on certain conditions.


Const EnhancedComponent= withAuthentication(WrappedComponent);

9. Context API:
• Use React Context to manage and share state across components, enabling conditional rendering based on context values.
<MyContext.Consumer>
{value => (value.isLoggedIn ? <p>Welcome, User!</p> : <p>Please log in.</p>)}
</MyContext.Consumer>

Choose the method that best suits your use case, readability, and maintainability. The appropriate approach often depends on the specific requirements
and structure of your React application.

⚫ Recap
10. In React, you control branching logic with JavaScript.
11. You can return a JSX expression conditionally with an if statement.
12. You can conditionally save some JSX to a variable and then include it inside other JSX by using the curly braces.
13. In JSX, {cond ? <A /> : <B />} means “if cond, render <A />, otherwise <B />”.
14. In JSX, {cond && <A />} means “if cond, render <A />, otherwise nothing”.
15. The shortcuts are common, but you don’t have to use them if you prefer plain if.

Rendering Lists

You will often want to display multiple similar components from a collection of data. You can use the JavaScript array methods to manipulate
an array of data.

import React from "react";


function ColorList({colors}){
return(
<ul>
{colors.map(color => (
<li key={color.id} style={{ backgroundColor: color.value }}>
{color.name}
</li>
))}
</ul>

)
}
function ListRend(){
const colorData=
[
{id :1 , name: 'Red' ,value: '#FF0000'},
{ id: 2, name: 'Green', value: '#00FF00' },
{ id: 3, name: 'Blue', value: '#0000FF' },
]
return(
<div>
<h3>Color List</h3>
<ColorList colors={colorData}> </ColorList>{}
</div>
);
}
export default ListRend;

16. Color List Component:


• The ColorList component takes a prop called colors, which is an array of color objects.
• Inside the render method of ColorList, we use the map function to iterate over each color in the array and create a list item
(<li>) for each one.
• The key attribute is crucial for React to efficiently update the DOM when the list changes. It should be a unique identifier for
each color.

New Section 1 Page 3


each color.
• The background color of each list item is set dynamically based on the color value.
17. App Component:
• The App component contains the main application logic.
• It defines an array called colorData with sample color data.
• It renders the ColorList component and passes the colorData array as a prop.
18. Rendering in JSX:
• JSX is used to dynamically render the color name and set the background color based on the color value.
This example is straightforward and demonstrates the basic concept of rendering a list. The colors are represented as a simpl e
array of objects, and each color is displayed in a list item with its name and background color.

import React from "react";


function ColorList({colors}){
const filterColor=colors.filter(color=>color.name.startsWith('R'));
return(
<ul>
{filterColor.map(color => (
<li key={color.id} style={{ backgroundColor: color.value }}>
{color.name}
</li>
))}
</ul>

}
function ListRenUsingFilter(){
const colorData=[
{id:1,name:'Red' ,value: '#FF0000'},
{id:2,name:'Green',value: '#00FF00'},
{ id: 3, name: 'Blue', value: '#0000FF' },
]
return (
<div>
<h2>Color List</h2>
<ColorList colors={colorData}></ColorList>
</div>
)
}
export default ListRenUsingFilter;

19. Keys in React:


• In React, a "key" is a special string attribute that you need to include when creating lists of elements or components.
• The key serves as a unique identifier for each item in the list.
20. Matching Array Items:
• React uses keys to match each component in the list with its corresponding item in the array.
• This matching process is crucial for React to understand how the array has changed, especially when items are added, removed, or
rearranged.
21. Handling Changes:
• When the array of items changes (due to sorting, insertion, deletion, etc.), React uses the keys to efficiently update the DO M tree.
• The presence of keys helps React identify which elements are added, which are removed, and which are updated.
22. React's Reconciliation:
• React performs a process called "reconciliation" during which it compares the new list of elements with the previous list, us ing keys to
match them.
• With well-chosen keys, React can infer the specific changes that occurred in the list and update the DOM accordingly.
23. Use Cases:
• Keys are especially important when dealing with dynamic lists in React, where items can change order, be added, or be removed .
• Without keys, React might have difficulty determining the correct updates to apply, leading to potential rendering issues or inefficiencies.
In summary, using keys is a best practice in React when rendering lists of components. It helps React efficiently manage upda tes to the UI,
ensuring that the DOM is accurately synchronized with changes in the underlying data. Well -chosen and stable keys contribute to a smoother
and more performant user interface.

Q > What do you mean by javascript functions are pure

In the context of programming languages, including JavaScript, a pure function is a type of function that has two main
characteristics:
1. Deterministic: The output of the function is solely determined by its input parameters. Given the same set of input parameters, a
pure function will always produce the same output. It does not rely on any external state or data.
2. No Side Effects: A pure function does not cause any observable side effects, meaning it does not modify any external state or
variables, and it does not perform any actions beyond computing its result. It only depends on its input parameters to produc e
output.

Here's an example of a pure function in JavaScript:

function add(a, b) {

New Section 1 Page 4


function add(a, b) {
return a + b;
}

This add function is pure because it takes two parameters and returns their sum. It doesn't modify any external state, and calling it
with the same arguments will always produce the same result.
In contrast, an impure function might rely on external variables, modify global state, or perform other actions that introduc e side
effects. Pure functions are generally easier to reason about, test, and maintain, as they exhibit a higher level of predictab ility and
encapsulation.

Which are impure functions ?


Impure functions are functions that do not adhere to the characteristics of purity. They either rely on external state or pro duce side effects. Here are some
examples of actions that can make a function impure:

let globalVar = 10;


function impureFunction(a) {
globalVar += a;
return globalVar;
}

In this example, the impureFunction modifies the global variable globalVar. This reliance on external state makes the function impure.

3. Modifying External State:


Let globalVar = 10;
function impureFunction(a)
{
globalVar += a; returnglobalVar;
}
In this example, the impureFunction modifies the global variable globalVar. This reliance on external state makes the function
impure.

4. Side Effects:
Function impurePrint(message)
{
console.log(message);
}
The impurePrint function has a side effect by logging to the console. Even though it doesn't modify external state, it performs an
action beyond computing its result, making it impure.

5. Dependency on External State:


Let externalVar = 5;
Function impureDependency(a)
{
returna + externalVar;
}
The impureDependency function relies on the external variable externalVar to compute its result. Changes to this external variable
can affect the function's output.

6. Non-Deterministic Behavior:
Function impureRandom()
{
returnMath.random();
}
7. The impure Random function is impure because it produces different results on each invocation, even with the same input. This
non-deterministic behavior makes it impure.

It's important to note that impure functions are not necessarily bad, but they may introduce complexities, especially when it comes
to reasoning about code, testing, and maintaining the system. Pure functions, on the other hand, provide benefits like predic tability
and ease of testing. Choosing between pure and impure functions often depends on the specific requirements and design goals o f
a given application.

Q > Keeping Components Pure

React assumes that every component you write is a pure function.This means that React components you write must always return the same JSX given the
same inputs:

You could think of your components as recipes: if you follow them and don’t introduce new ingredients during the cooking
process, you will get the same dish every time. That “dish” is the JSX that the component serves to React to render.

New Section 1 Page 5


1. Independence
Components should be self-contained and not modify objects or variables that existed before rendering. Modifying external state can lead to unintended
side effects and make the application harder to reason about.

const Counter = ({ counter }) => {


// Not modifying any external state, following independence
return <div>{counter}</div>;
};

Here, the Counter functional component is following the independence principle by not modifying any external state.

2. Predictable Output:

const UnpredictableComponent = ({ value }) => {


// Using Math.random() results in unpredictable output
const randomValue = Math.random();

return <div>{value + randomValue}</div>;


};
The UnpredictableComponent still introduces unpredictability by using Math.random()

Ensuring that a component produces the same JSX given the same inputs is essential for predictability and stability. It enables React to optimize rendering
through mechanisms like memoization and shouldComponentUpdate in the case of class components.

Rendering Independence:
• React components can render at various times, and their rendering order isn't guaranteed. Therefore, components should not
depend on the rendering sequence of others. Each component should operate independently to maintain a modular and
scalable architecture

const ParentComponent = () => {


return (
<div>
<ChildComponent />
<AnotherChildComponent />
</div>
);
};

const ChildComponent = () => {


// Rendering order independence is maintained
return <div>Child Component</div>;
};

const AnotherChildComponent = () => {


return <div>Another Child Component</div>;
};

1. Immutable Inputs:
• Mutating inputs (props, state, or context) directly goes against the principles of immutability. Instead, components should
create new objects or arrays when updates are needed. This ensures that changes in one component do not inadvertently
affect other components relying on the same input.

import { useState } from 'react';

const MutableComponent = () => {


// Mutating state directly violates immutability
const [count, setCount] = useState(0);

const incrementCount = () => {


// Better: Use setCount to update state immutably
setCount((prevCount) => prevCount + 1);
};

return (
<div>
<p>{count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
};

2. Logic in JSX:
• Expressing component logic within the JSX makes the component's behavior more declarative and easier to understand. By

New Section 1 Page 6


• Expressing component logic within the JSX makes the component's behavior more declarative and easier to understand. By
keeping logic close to where it's used, you improve code readability. However, complex logic or state updates are typically
handled in event handlers or useEffect hooks.

const LogicInJSX = ({ isLoggedIn }) => {


// Embedding logic in JSX for declarative rendering
return (
<div>
{isLoggedIn ? <p>Welcome, User!</p> : <p>Please log in</p>}
</div>
);
};

3. Practice Pure Functions:


• Writing pure functions within the context of React involves adhering to the principles of functional programming. This means
avoiding side effects, relying on external state, and ensuring that functions are deterministic. Pure functions in React ofte n
involve transforming input data into JSX or performing calculations without modifying external state.
In summary, these principles collectively contribute to writing clean, predictable, and maintainable React code. By adhering to these
guidelines, you create components that are easier to understand, test, and reason about, ultimately enhancing the robustness and
performance of your React applications.

const PureFunctionComponent = ({ value }) => {


// Pure function: Same input, same output
const doubledValue = double(value);

return <div>{doubledValue}</div>;
};

const double = (x) => {


return x * 2;
};

In the functional component, the double function remains a pure function.


These functional component examples showcase adherence to the principles discussed, promoting clean and maintainable React
code.

Understanding Your UI as a Tree

New Section 1 Page 7

You might also like