0% found this document useful (0 votes)
7 views18 pages

Unit - II

The document covers conditional rendering in React, explaining how components can render different content based on state and conditions using if-else statements, logical operators, and switch cases. It also discusses the importance of the key prop for list management and the use of refs for accessing DOM elements. Additionally, it elaborates on props and state management, including props validation and the use of the useState hook for managing component state.

Uploaded by

Akash Kale
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)
7 views18 pages

Unit - II

The document covers conditional rendering in React, explaining how components can render different content based on state and conditions using if-else statements, logical operators, and switch cases. It also discusses the importance of the key prop for list management and the use of refs for accessing DOM elements. Additionally, it elaborates on props and state management, including props validation and the use of the useState hook for managing component state.

Uploaded by

Akash Kale
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/ 18

Conditional Rendering and List

● Conditional Rendering in React -

1. A component can render specified content in UI.


2. It is defined by using “render()” method.
3. In various situations a component must able to render different types of contents.
4. You can design component with conditional rendering, so that it can render
content according to state and situation.It requires the traditional JavaScript
operator like “if, switch, ternary etc.

● If-else statement

An if…else statement will execute the actions contained in the if block when the
condition is satisfied. Otherwise, it will execute the actions contained in the else block.

In JSX, you are able to use JavaScript code with markup to render dynamic values within
your application. JSX uses curly braces ({ and }) to signify expressions that need to be
interpreted prior to rendering. The caveat, however, is that there is a limit to what can be
done within such braces.

Example

function App() {

let a=30;

let msg="";

if(a>=10)

msg="a is greater than or equal 10";


}

else

msg="a is less than 10";

return (

<>

<p>{msg}</p>

</>

);

export default App;

● Logical && operator (and and)

If the condition is true,the expression after the logical && operator will be the output. If
the condition is false,React ignores and skips the expression.

If the condition is true, the element right after && will appear in the output.If it is false ,
React will ignore and skip it. Note that returning a falsy expression will still cause the
element after && to be skipped but will return the falsy expression.

true && expression always evaluates to expression, and false && expression always
evaluates to false.
function App() {

let a=40;

let b=10;

let c=100;

let msg="";

if(a>=b && a>=c)

msg="a is greater than b and c";

else if(b>=a && b>=c)

msg="b is greater than a and c";

else

msg="c is greater than a and b";

return (

<>
<p>{msg}</p>

</>

);

export default App;

Operators

preventing component from rendering

● Switch case operator

switch case operator to handle the conditional rendering of these multiple states.

The switch statement in JavaScript is used to evaluate an expression and execute the
corresponding code block based on the expression’s value. In React, we can use switch
statements inside a component to conditionally render different elements or components
based on a particular value.

switch statements can be used inside a component to render different content based on a
particular condition.

function App() {

let a=40;

let b=10;
let addition="addition";

let sub="substraction";

let ch="addition";

let action=0;

switch(ch)

case "addition" :

action=parseInt(a)+parseInt(b);

break;

case "sub" :

action=parseInt(a)-parseInt(b);

break;

default:

action="your choice is wrong";

return (

<>

<h3>Select Any Action</h3>

<h4>{addition}</h4>
<h4>{sub}</h4>

<h5>Your Area Selected Action is {ch}</h5>

<h5>{ch}={action}</h5>

</>

);

export default App;

List and Keys

● React key Prop

The key prop is a unique identifier that React uses to efficiently manage and update
elements within a list. When rendering a list of elements, it is crucial to assign a unique
key to each element to help React differentiate between the items and perform updates
more efficiently.React's key prop gives you the ability to control component instances.

If a unique value is required, we need to pass keys as a prop with a distinct prop name.

function App(props) {

return (

<>
<h3>Your name is {props.name}</h3>

</>

);

export default App;

index.js file

root.render(

<React.StrictMode>

<App name="raju"/>

</React.StrictMode>

);

● Map function to iterate the List

JavaScript array map() method is used to iterate through the data in the form of an array.
This map() in react is used to create the list by iterating the data and transforming it into
the list components using HTML tags.

● References

ReactJS Refs are used to access and modify the DOM elements in the React Application.
It creates a reference to the elements and uses it to modify them.
Short for “reference”, refs are a way to access underlying DOM elements in a React
component.

Refs is the shorthand used for references in React. It is similar to keys in React. It is an
attribute which makes it possible to store a reference to particular DOM nodes or React
elements. It provides a way to access React DOM nodes or React elements and how to
interact with it. It is used when we want to change the value of a child component,
without making the use of props.

● useRef

The useRef Hook allows you to persist values between renders.

It can be used to store a mutable value that does not cause a re-render when updated.

It can be used to access a DOM element directly.

useRef() only returns one item. It returns an Object called current.

When we initialize useRef we set the initial value: useRef(0).

const ref = useRef(initialValue)

● Create Refs

Refs are created using React.createRef() and attached to React elements via the ref
attribute. Refs are commonly assigned to an instance property when a component is
constructed so they can be referenced throughout the component.

createRef always returns a different object. It’s equivalent to writing {current:null}


yourself.
In a function component,you probably want useRef instead which always returns the
same object.

● Access Refs

In React, when a ref is passed to an element in render using the ref attribute, the
underlying DOM element or React component becomes accessible at the current property
of the ref.

Refs are a function provided by React to access the DOM element and the React elements
created in components. They are used in cases where we want to change the value of a
child component, without making use of props and state.

● Event Binding types:


1. Bind() method

The bind() is an inbuilt method in React that is used to pass the data as an
argument to the function of a class based component.

Syntax: this.Function.

The bind() function creates a new bound function

The simplest use of bind() is to make a function that, no matter how it is called, is
called with a particular this value
● Arrow Function

The arrow function is a new feature of ES6, introduced in ReactJS 16. It allows the
developer to create a function that has lexical “this” binding and no arguments.

Arrow functions offer a compressed and short version of a function expression and need
fewer keystrokes than regular JavaScript functions from the developer and can be used as
a simpler alternative to functions within class components and functional components
and event handlers in React.

Arrow functions are always anonymous, meaning there is no need to use the keyword
“function” when defining them. They also do not have their own this value, meaning that
this inside an arrow function will refer to the one where it was created rather than where
it was called from.

The third difference between regular JavaScript functions and arrow functions is that all
arguments passed into an arrow function must be pre−defined, because there is no need
for them to be assigned as default values like with regular JavaScript functions.

It allows you to create functions in a cleaner way. The arrow function is a compressed
and shorter version of the function expression. It requires fewer keystrokes by
developers.

Props and State:

What is a state
The state is a built-in React object that is used to contain data or
information about the component. A component's state can change
over time; whenever it changes, the component re-renders.

The change in state can happen as a response to user action or system-generated


events and these changes determine the behavior of the component and how it will
render.

● A state can be modified based on user action or network changes


● Every time the state of an object changes, React re-renders the component to
the browser
● The state object is initialized in the constructor
● The state object can store multiple properties
● this.setState() is used to change the value of the state object
● setState() function performs a shallow merge between the new and the
previous state

Use and role of the state

React components has a built-in state object. The state object is where you store
property values that belong to the component. When the state object changes, the
component re-renders.

React's state is great for handling data that's specific to a single component. It's simple
and lightweight, making it suitable for components that don't need to share data widely.
You can modify state using the setState function.

What is Props
In ReactJS, the props are a type of object where the value of
attributes of a tag is stored. The word “props” implies “properties”, and
its working functionality is quite similar to HTML attributes. Basically,
these props components are read-only components.
props validation

Props are an important mechanism for passing the read-only attributes to React
components. The props are usually required to use correctly in the component. If it is not
used correctly, the components may not behave as expected. Hence, it is required to use
props validation in improving react components.

Props validation is a tool that will help the developers to avoid future bugs and problems.
It is a useful way to force the correct usage of your components. It makes your code more
readable. React components used special property PropTypes that help you to catch bugs
by validating data types of values passed through props, although it is not necessary to
define components with propTypes. However, if you use propTypes with your
components, it helps you to avoid unexpected bugs.

Validating Props
App.propTypes is used for props validation in react component. When some of the props
are passed with an invalid type, you will get the warnings on JavaScript console. After
specifying the validation patterns, you will set the App.defaultProps.

Syntax:
​ class App extends React.Component {
​ render() {}
​ }
​ Component.propTypes = { /*Definition */};

ReactJS Props Validator


ReactJS props validator contains the following list of validators.
SN PropsType Description

1. PropTypes.any The props can be of


any data type.

2. PropTypes.array The props should be


an array.

3. PropTypes.bool The props should be


a boolean.

4. PropTypes.func The props should be


a function.

5. PropTypes.number The props should be


a number.

6. PropTypes.object The props should be


an object.

7. PropTypes.string The props should be


a string.

8. PropTypes.symbol The props should be


a symbol.
9. PropTypes.instanceOf The props should be
an instance of a
particular JavaScript
class.

10. PropTypes.isRequired The props must be


provided.

11. PropTypes.element The props must be


an element.

12. PropTypes.node The props can render


anything: numbers,
strings, elements or
an array (or
fragment) containing
these types.

13. PropTypes.oneOf() The props should be


one of several types
of specific values.

14. PropTypes.oneOfType([PropTypes.strin The props should be


g,PropTypes.number]) an object that could
be one of many
types.
ReactJS Custom Validators
ReactJS allows creating a custom validation function to perform custom validation. The
following argument is used to create a custom validation function.

○ props: It should be the first argument in the component.


○ propName: It is the propName that is going to validate.
○ componentName: It is the componentName that are going to validated again.

Passing data between multiple component

managing component state

React components have their own local state that can be managed independently. State is
initialized using the useState hook and can be updated using the setState function.
Components can access and modify their local state directly. To initialize state, we can
use the useState hook and provide an initial value.

The local state can be managed using React's setState() method. Context: React's
context API allows you to pass data through a component tree without having to pass
props down manually at every level.

React state management is a process for managing the data that React components need in order
to render themselves.

You might also like