React JS1
React JS1
React JS1
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>:
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.
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(props) {
let person = props.person;
let size = props.size;
// ...
}
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.
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.
Conditional rendering in React involves rendering different content or components based on certain conditions.
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:
2. Ternary Operator:
• Use the ternary operator for simple conditions.
{isLoggedIn ? <p>Welcome, User!</p>: <p>Please log in.</p>}
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>;
}
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>} />
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.
)
}
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;
}
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;
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.
function add(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.
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.
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.
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.
Here, the Counter functional component is following the independence principle by not modifying any external state.
2. Predictable Output:
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
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.
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
return <div>{doubledValue}</div>;
};