0% found this document useful (0 votes)
3 views

Components In REACT

The document provides an overview of components in React, highlighting their role as the fundamental building blocks of user interfaces. It explains the two main types of components (Class and Function components), how to create and render them, and the concept of props for passing data between components. Additionally, it covers advanced topics such as conditional rendering, event handling, and component composition and decomposition.

Uploaded by

Mohit kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Components In REACT

The document provides an overview of components in React, highlighting their role as the fundamental building blocks of user interfaces. It explains the two main types of components (Class and Function components), how to create and render them, and the concept of props for passing data between components. Additionally, it covers advanced topics such as conditional rendering, event handling, and component composition and decomposition.

Uploaded by

Mohit kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Components In React

Building Block Of UI
Components Introduction

A React component represents a small chunk of user interface in


a webpage. A Component is one of the core building blocks of
React. The primary job of a React component is to render its user
interface and update it whenever its internal state is changed. In
other words, we can say that every application you will develop
in React will be made up of pieces called components.
Components make the task of building UIs much easier

Components in React basically return a piece


of JSX code that tells what should be rendered
on the screen
Components Introduction
Types of Components In ReactJS
When creating a React component, the component's
name MUST start with an upper case letter. In React, we
mainly have two types of components.

Class Components
A class component must include the extends React.
Component statement. This statement creates an
inheritance to React. Component, and gives your component
access to React. Component's functions. The component also
requires a render() method, this method returns HTML
Components Introduction
Creating A Class Component
import react from ‘react’
class Calculator extends React.Component {
render() {
return <h2>Hi, I Will Calculate
Everything!</h2>;
}
}
Creating A Function Component
function Calculator() {
return <h2>Hi, I Will Calculate
Everything!</h2>;
}
Components Introduction
Rendering A Component
Now your React application has a component called
Calculator, which returns an <h2> element. To use this
component in your application, use similar syntax as normal
HTML.
<Calculator />
To display Calculator component in the root element

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Calculator />);
OR
const element=<Calculator/>
root.render(element)
Components Introduction
Separating The Concern
React is all about re-using code, and it is recommended to
split your components into separate files.To do that, create a
new file with a .js file extension and put the code inside it.
Create a file “Calculator.js”
function Calculator() {
return <h2>Hi, I Will Calculate
Everything!</h2>;
}
export default Car;

To be able to use the Car component, you


have to import the file in your application
Components Introduction
Importing A Component
Now we import the "Calculator.js" file in the application main
component(index.js), and we can use the Calculator
component as if it was created here

import React from 'react’;


import ReactDOM from 'react-dom/client’;
import Car from './Car.js';
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
Composing Components
Components Within Components
It is possible to create nested components in ReactJS. We can simply add a
component inside other components which add a cohesive relation between
components.
function Button() {
return <button>Hi Click Me To Perform Addition!</button>;
}
function Calculator() {
return (
<>
<h1>Hi! I Can Calculate Numbers</h1>
<Button />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Calculator />);
Decomposing Components
Decomposing a Component means breaking down the component into smaller components
import React from 'react';
import ReactDOM from 'react-dom';
const Input=()=>{
return(
<div>
<input type="text" placeholder="Enter Text.." />
<br />
<br />
</div>
);
}
const Button=()=>{
return <button type = "submit">Submit</button>;
}
const Form=()=>{
return (
<div>
<Input />
<Input />
<Button />
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
Props In React
Props also termed as properties are arguments passed into react
components and they are passed to components through HTML
attributes.
We know that everything in ReactJS is a component and to
pass in data to these components, props are used. Whenever we
call child components from parents we can pass data as props.
This helps the parent component communicate with the child

To send props into a component


const login=<Login username=“admin”
password=“admin123”/>

To use props int the component


function Login(props){
return <h2>Welcome {props.username}</h2>
}
Props In React
Creating Components Having Props
function Stadium(props) {
return <h1>Inside {props.name} in {props.city}</h1>;
}
function Player() {
return (
<>
<h2>I Will Play My First Match</h2>
<Stadium name=“Eden Garden“ city=“Kolkata” />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Player />);

Here we are passing two string values from Parent


Component(Player) to props and they will be treated like
variables within the child component(Stadium)
Props Drilling
Passing Objects In Props
function Stadium(stadium) {
return <h1>Inside {stadium.info.name} in {stadium.info.city}</h1>;
}
function Player() {
const stadiumInfo={name:’Eden Gardens’,city:’Kolkata’}
return (
<>
<h2>I Will Play My First Match</h2>
<Stadium info={stadiumInfo}/>
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Player />);
React Props are read only. You will get an error if you will try to
modify their values inside the component
Props Drilling
Default Props
Like default arguments we can also set a default value in ReactJS Props.
Default value is used when parent component do not passes the prop to
the child component, default value is passed to the props.

Default Props In Action

Defining Default Props


import React from "react";
const Stadium=({sname='Ekana',scity='Lucknow'})=>{
return <h1>Inside {sname} In {scity} </h1>
}
export default Stadium

Using Default Props


<Stadium sname=‘Eden Garden’ />

Here scity is not passed by parent component so the


default value Lucknow will be used in child component
React Events
Just like HTML DOM events, React can perform actions based on
user events. React has the same events as HTML: click, change,
mouseover etc. React Events are written in camelCase syntax
onMouseOver instead of onmouseover and written inside curly
braces onClick={event} instead of onclick=“event()”

Recat Event
<button onClick={hitsix}>Take the Shot!</button>

HTML Event
<button onclick=“hitsix()">Take the Shot!</button>
React Components Event
Adding event inside a react component is as simple as passing a
function to the child component as a prop. Here we are adding
hitsix event to cricket component

function Cricket() {
const hitsix = () => {
alert(“Scorer Add Six Run To Score!!!");
}

return (
<button onClick={hitsix}>Take the shot!</button>
);
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Cricket />);
React Components Event
To pass an argument to an event handler, use an arrow operator.
Send “6 Runs” as a parameter to the hitsix function using arrow
function

function Cricket() {
const hitsix = (value) => {
console.log(`Add ${value} To Score`)
}

return (
<button onClick={()=>hitsix(“6 Runs”)}>Take the
shot!</button>
);
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Cricket />);
React Components Event
React Event Object
Event handlers have access to the React event that triggered the
function.
In our example the event is the "click" event

function Cricket() {
const hitsix = (value,event) => {
console.log(`Add ${value} To Score On ${event.type}`)
}

return (
<button onClick={(event)=>hitsix(“6 Runs”,event)}>Hit
Shot</button>
);
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Cricket />);
Conditional Rendering
In React, you can conditionally render components. There are several
ways to do this.

if statement
We can use the if JavaScript operator to decide which component to
render
function MissedGoal() {
return <h1>MISSED!</h1>;
}

function MadeGoal() {
return <h1>Goal!</h1>;
}
function Goal(props) {
const isGoal = props.isGoal;
if (isGoal) {
return <MadeGoal/>;
}
return <MissedGoal/>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));


Conditional Rendering
Using Logical Operator
Another way to conditionally render a React component is by using the
&& Operator. We can embed JavaScript expressions in JSX by using curly
braces carrier
function Career(props) {
const {centuries} = props.info;
return (
<>
<h1>Centuries In Career</h1>
{centuries > 0 &&
<h2>
You have {centuries} Centuries in your career.
</h2>
}
</>
);
}

const details
={runs:13432,centuries:21,manofthematch=17,sixes=311}
const root = ReactDOM.createRoot(document.getElementById('root'));
Conditional Rendering
Using Ternary Operator
Another way to conditionally render elements is by using a ternary
operator( ?: )
condition ? true : false

function Goal(props) {
const isGoal = props.isGoal;
return (
<>
{ isGoal ? <h1>You Scored Goal</h1>:<h1>You Missed
Goal</h1>}
</>
);
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);
Preventing Rendering
It might happen sometimes that we may not want some
components to render. To prevent a component from rendering we
will have to return null as its rendering output

function Message(props) {
if(!props.isVisible)
return null;
else
return <h1>{props.text}</h1>;
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Message text=“My Message Is Here”
isVisible={true}/>);

You might also like