KEMBAR78
ReactComponents EtPlus | PDF | Java Script | Method (Computer Programming)
0% found this document useful (0 votes)
28 views62 pages

ReactComponents EtPlus

This document provides an overview of React components, detailing their definition, types, and advantages such as reusability and maintainability. It explains how to create and use components, including functional and class components, and introduces the concept of Higher-Order Components (HOCs) for code reusability. Additionally, it covers the importance of props in managing data flow between components, emphasizing the one-way data flow principle in React.

Uploaded by

Wissem Chehaider
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views62 pages

ReactComponents EtPlus

This document provides an overview of React components, detailing their definition, types, and advantages such as reusability and maintainability. It explains how to create and use components, including functional and class components, and introduces the concept of Higher-Order Components (HOCs) for code reusability. Additionally, it covers the importance of props in managing data flow between components, emphasizing the one-way data flow principle in React.

Uploaded by

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

React Components

Introduction to Component

Introduction to Component
So far we have learned what React and JSX are. We have learned their
functionalities, their advantages and their limitations. These are big steps
we’ve made but there’s a lot more cool stuff waiting for us!
In this chapter, we’re going to learn more about one of the most important
features in React: ‘component’, so we’re going to see:

 What is a component?
 How to create a component?
 What are the various component types?
 How to use a component?
 What is HOC in React?

What is a Component ?
First thing’s first, before we start off by defining the React component,
let’s have a look at the definition of a component.
By a simple search on Google, we encounter a lot of complicated
definitions but let’s try and keep it simple. A component is a piece of code
that can be reused and made to cooperate with other components to
create a UI.
Let’s have a look at the image below and see how it’s structured:
Advantages of using components
Working with components makes web development much easier. The
reasons are:

 Reusability:
Every implemented component can, if not must, be reused while building
our web application.
Let’s take the example of a sidebar on a dashboard, it will be used
whichever page we display.

 Maintainability:
Every component is implemented separately from the others so it can be
maintained without affecting other UI compositions.

 Platform independence:
In reality, the web components are built using HTML, CSS and JavaScript
which make it a cross-platform.

 Privacy:
Since every component is built to operate alone, that ensures that its
content is more private than shared code.

What is a React Component?


Components are the building blocks of any React app. You will notice that
a typical React app will have plenty of them.
Simply put, a component is a JavaScript class or function that optionally
accepts inputs i.e. properties or props and returns a React element that
describes how a section of the UI (User Interface) should look like.
// My first component

const Greeting = () => <h1>Hello World from my first component!</h1>;

This is a functional component (called Greeting) written using ES6’s arrow


function syntax. It takes no props and returns an h1 tag with the text “Hello
World today!”

Assessment: Quiz
A component is an external library used by React.

True False
A component is a set of code that generates a specific UI.

True False
Component is a JavaScript approach only.

True False

Components Types
Types of components
As we have said earlier, there are two types of React components, this
division happened before the appearance of React version 16.8.
But for the purpose of learning, it’s best if we know them.

The two types of React components are:

 Class components: referring to JavaScript classes.


 Functional components: referring to JavaScript function.

Class Components
If you read articles on the Internet about React components, you will find
the following names that refer to class components:
Smart Component
Before React 16.8, the logic was only implemented in this type of
component, because of the advantage that classes give over functions.

Stateful Component
Before february 2019, only class could hold and manage JavaScript State.

Container Components
It’s called so, because usually it holds/contains other numeros (mostly
functional) components.

Enough theory, let’s take a look at an example:


class Greeting extends React.Component {

render(){

return <h1>Hi, I’m a smart component!</h1>;

Functional Components:
These components are purely presentational and are simply represented
by a function. This function optionally takes props and returns a React
element to be rendered to the page.

Generally, it is preferred to use functional components whenever possible


because of their predictability and conciseness. Since, they are purely
presentational, their output is always the same if we give them the same
props.

You may find functional components referred to as stateless, dumb or


presentational in other reading material. All these names are derived from
the simple nature that functional components take on.

 Functional because they are basically functions


 Stateless because they do not hold and/or manage state
 Presentational because all they do is output UI elements

But always remember, this is all before developing with React 16.8.
For now, all functional component can do the same things as class based
component.
import React from "react";

const Greeting = () => <h1>Hello World from my first component!</h1>;


export default Greeting;

Assessment: Quiz
What are the types of React components?

class object function variable


The functional component is:

stateless statefull
After which version, we can only use functional components:

16.8 19.20 16.1.1

Create Components
Creating our first component:
After all that talk about components, it’s time to get our hands dirty.
Let’s create our first react component!
Creating a component is much easier than you think. In practice, a
component is simply a function that returns JSX, that’s all we need to
create a component.
Using JavaScript’s power, we can manipulate these functions as we wish.
We are going to create the component Greeting that we’ve seen before.
It’s very simple. Just follow the instructions:

1. Create the project in the src folder,


2. Open the App.js,
3. Then, copy-paste this code.

import React from "react";

const App = () => {

return (

<>

<h2>Hello from my first component !!</h2>

</>

);

};

export default App;


Output

Congratulation ! You have created your first component. And YES! The App.js is
also a component. We will get to know it more in the next slides.

What should we remember?


There are a few things that you should notice about that first example, the
first one is the import React from "react"; well it’s mandatory since we
work with JSX and the export default App; this is also a mandatory action
that must be performed. We’ll explain its necessity. Remember the course
on ES6, and how it made our life much easier as a developper. Time to
rewind and take advantage of it.

In order to separate the components from each other, we have to use the
JavaScript modularity.

React also give us the possibility to use the named exports and the default
exports

The last thing that you should notice is that the component is starting with
an uppercase letter. That’s necessary so we do not confuse it with simple
HTML tags.

Default export
Similar to JavaScript file, we can export our component, as the example
below shows, using the keyword export default.
const MyFirstComponent = () => {

return (

<>

<h2>Hello from my first component !!</h2>

</>

);

};

export default MyFirstComponent;

By doing that we’ve made the file MyComponent.js export automatically the
component MyFirstComponent.

Named exports
The other way to export a component is by the named export. Let’s take a
look at the example.

This is how we can export more than one component from a single file.
import React from "react";

export const MyFirstComponent = () => {

return (

<>

<h2>Hello from my first component !!</h2>

</>

);

};

export const MySecondComponent = () => {

return (

<>

<h2>Hello from my second component!! </h2>

</>

);
};

Best Practices for Creating a


Component:
After creating our first component, here is a list of some common best
practices that we should know:

 Keep components small and function-specific:

o Function-specific components can be standalone, which makes


testing and maintenance easier.
o Each small component can be reused across multiple projects.
o With smaller components, it’s easier to implement
performance optimizations.
o It’s easier to update smaller components.
o Bigger components have to perform harder and may be
difficult to maintain.
 Name the component after the function:
It’s a good idea to name a component after the function that it
executes so that it’s easily recognizable.

 Keep them all in a single folder:


Keep all files relating to a component in a single folder, including
styling files.

 Reusability is important.

Fill in the blanks Solution


import React from 'react' const Car = () => { return <h2>Hi, I am a Car!</h2>; }

Using components
Using a Component
After creating our first component, it’s time to use it.

To make it happen, we will return again to JavaScript modularity. In order


to use any external module in our local file, we should import it first.
Let’s see an example to consolidate this.

MyFirstComponent.js
import React from "react";
const MyFirstComponent = () => {

return <h1> hello from my first component </h1>;

};

export default MyFirstComponent;

App.js
import React from "react";

import MyFirstComponent from "./MyFirstComponent";

const App = () => (

<>

<MyFirstComponent />

</>

);

export default App;

Output

Using a Component
Buckle up! It’s time we started creating things.
As we can see, we find the component MyFirstComponent inside the App.
It’s only right to ask if the constant App is a component or not. The answer
is: Yes, a component can be composed of many other components.
const App = () => {

return (

<div>

<Header /> // Header Component

<Footer />

// Footer Component

</div>

);

};

When one component uses another like this, a parent-child relationship is


formed. In above example :

 The App component is the parent to the Header and Footer


components.
 The Header and Footer components are the child of the App
component.

Using a component as a root


We talked earlier about the ReactDom.render() method in the JSX
chapter. Basically, that method exists in the index.js file. This file is called
the root component.
import React from "react";

import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");//We call this a


“root” DOM node because everything inside it will be managed by React
DOM.

ReactDOM.render(<App />,rootElement);

You can notice that applications built with React have a single root DOM
node.

Assessment: Quiz
A component can render another component.

True False
Applications built with React have many root components:

True False
To establish a parent-child relationship, component A should render component B.

True False

Component: HOC
What is HOC?
We have seen the higher order function in JavaScript, which is a function
that accepts another function as a parameter.

Well, React clones and imitates that functionality with a component, so it


gives us the possibility to create a Higher-Order Component which is a
component that accepts a component as a parameter.
Essentially, a higher-order component is a function that takes a
component and returns a new component.

Why HOC?
In software development, there is one important principle that is
commonly used by the name of « DRY » (which stands for "Don’t Repeat
Yourself").

Creating a simple utility function, that is used across several parts of the
codebase is something you may have done repeatedly. You are essentially
following the DRY principle by doing so. You are reusing the same utility
function, without repeating the code.
In React, one of the ways to follow “DRY” across components, is to use the
Higher-Order Component (HOC) concept. We can share common
functionalities without repeating code.

Example of HOC
In this example, we will add a waiting message on the wrapped
component. Don’t get too overwhelmed by this strange code. We’ll break
it down later.
import React from "react";

const higherOrderComponent = WrappedComponent => {

class HOC extends React.Component {

state = {

isLoading: false

};

render() {

return this.state.isLoading ? (

<h1>Wait a moment...</h1>

) : (

<WrappedComponent />

);

return HOC;

};

Assessment: Quiz
A HOC is a component that uses another component

True False
A HOC is a component that accepts another component as a parameter

True False
A HOC can only be a Class component

True False

Common Mistakes
Returning multiple nodes:
Since the component is only but a JavaScript function, and we know that
JavaScript functions can only return a single object, value or item,
therefore, the component can only return one JSX element.
Granted, it all seems a bit overcomplicated. Here is the right way to do it.
We wrap all the selected elements inside a single element div or section or
any other wrapper of our choice. Take a look at the example below.
const MyComponent = () => {

// return multiple root node

// WRONG!

return (

<Comp1 />

<Comp2 />

// this code will trigger an error

// Parse Error: Adjacent JSX elements must be wrapped in an


enclosing tag

The correct way to do it:


return (

<div>

<Comp1 />

<Comp2 />

</div>
);

React fragment
Naturally, the div or section or any other HTML container inherently have
default CSS properties that could affect our design.
To sidestep these default properties, React gives us
the React.Fragment which is a wrapper that has no effect on the CSS. A
React fragment cannot be styled.

Take a look at its syntax in the provided example:


return (

<React.Fragment>

<div />

<div />

</React.Fragment>

);

//this also is valid

return (

<>

<div />

<div />

</>

);

Using absolute paths


Using an absolute path can be a little bit tricky and it can lead to a lot of
problems when trying to reuse the component.

⇒ So, we advise you to use the relative paths instead.


//relative path

import MyFirstComponent from "./MyFirstComponent";


//absolute path

import MyFirstComponent from '/src/component/MyFirstComponent'

Assessment: Quiz
Can we return multiple nodes in the function return

True false
React fragment can be styled

True False
Using absolute path can create path conflict.

True False

Conclusion
Time to Recap!
We’ve made some impressive progress. We now know how components
work and how we can utilize them to develop modular React code that
represents different sections of our user interface.

In summary, React components are the building block of any react


application, components give us the ability to reuse the same codebase.
React also proposes two types of components, in addition to the ability of
using the HOCs pattern in making the building of our UI much easier.

React Props
Understanding Props
Introduction
Like most great inventions, there’s always a simple core idea that holds
everything together. In React, it’s arguably the props system that allows
us to treat React components just like JavaScript functions.
In this chapter, we are going to be looking at the React Props, including:
What are these props?

How to create a prop?

The different types of props.

What are the children props?

How to define the default props?

What are the prop types?

One-way data flow


Remember when we presented React's features? we spoke about the one-
way data flow. What does it mean, you ask?

This approach means that the data can only travel, in a unidirectional
fashion, from a parent to a child component (top to bottom) and not the
other way around. Unlike other libraries and the frameworks, React makes
sure that this feature remains in its architecture.

The reason behind React keeping this perk in its ecosystem is because the
one-way data flow makes it easier to trace the data and it’s changes over
the component tree, it sounds a little bit confusing but let’s view an
illustration to further clarify the concept.

What are props?


To make this unidirectional data flow possible, React uses props.
Props or properties are the tools that React uses to pass data from
parent to child elements.
Let’s think of it as a parameter in a JavaScript function.
We can change the value of this parameter but the sets of instructions to
be executed remain the same.
Take your facebook page for example. You will find your name on the
right, next to your picture.
From a coding perspective, facebook developers can't create a customized
navbarfor every profile.
This is only possible and achievable using React props.
The structure of these elements will be fixed and the content (name,
image url...) will be received as a props.

JS example
Here is another example to consolidate what we were just talking about.
function Greeting(name) {

return "hello " + name;

console.log(Greeting('Jon Snow'))// it will display "hello Jon Snow"


console.log(Greeting('Ramsay Bolton')) // it will display "hello Ramzay
Bolton"

console.log(Greeting('I am nobody')) // it will display "hello I am


nobody"

The Greeting function receives a name as an argument. However, with


whichever name we set, it will still display a concatenated hello alongside
the name.

React example
Now let’s try the same idea with a React component.
function Greeter(props) {

return <h1>hello {props.name}</h1>;

// And invoking the <Greeter/> component…

const App = () => {

return (

<div>

<Greeter name="world" /> {/* 💥 "world" is the prop value*/}

<Greeter name="I am the King" /> {/* 💥 "I am the King" is the prop
value*/}

</div>

);

};

export default App;


Output

Let's recap!
React Props are like function arguments in JavaScript and attributes in
HTML. To send props into a component, use the same syntax as HTML
attributes:
<Greeter name="world" />

function Greeter(props) {

return <h1>hello {props.name}</h1>;

As we can see, the component Greeter receives the name as a props and
displays it in an h1 tag. Another thing to keep in mind is that props are an
object and whatever we pass as attributes in the component is called in
the parent.
Notice : Props are immutable which mean that the child can only read the
content of a props. It cannot change it.

Assessment: Quiz
What is a prop?

It is a special keyword in React. It is a package used by React. It is a


variable name.
A prop should only be a string.

True False
A prop is passed as a parameter to the component.
True False

Using props
Creating our first prop
Similar to an HTML attribute, in order to send a props from a parent to a
child component, we add the props as an attribute in the component call
process. Here is an example to better understand this.
<Welcome name="Sara" />;

A component can have an unlimited number of props, meaning that we


can pass as many props as we wish. Take a look at this example :
<Welcome name= 'Sara' lastName = 'Smith' Age='27'/>

Please consider that the names we give to props are personalized.


Even though we can call the props whatever we want, there are some best
practices to follow:
The name should be significant and meaningful so others can understand
the props' value.
Use lower camel case (e.g. isActive).
keep the name short ( < 50 characters ).

Props should be descriptive. Props describe what a component does and


not why it does it. A common mistake is naming props after the current
user or the current environment. For example :
hasSubmitPermission describes the permission of the user and the reason
for variation but not the component itself. A better name could be
hasSubmitButton. i.e.<MyForm hasSubmitButton={user.canSubmit} />

Using props
It’s time to use our first props after creating it!
First thing to do when using props is to pass it as a parameter to the
component's function.
// we always use the keyword props in the function parameter

const Welcome = props =>{

return (

<h1>

`Hello`

</h1>
)

We can use any parameter name but by convention we use the


keyword props.

The props object


If we perform a console.log() on the received props, we’ll find the following
result:

App.js
const App = () => (

<div>

<Welcome name="Sara" />

</div>

);

Welcome.js
const Welcome = props =>{

console.log(`props:`,props)

return (

<h1> welcome </h1>

Output

As we can see in the example above, even if the props were passed as a
string, it still had arrived as an object to the child component.
the props object
In the previous slide, we saw that props always arrive as an object to child
components.
In order to use it, we need to treat it as an object. We can access the
desired value by using the dot property accessor.
const Welcome = props =>{

console.log(`props:`,props)

return (

<h1> welcome {props.name}</h1>

Rules of Props
We‘ve said earlier that props are immutable but what if we try to change
its value?
Take a look at the example below :
const Welcome = props =>{

console.log(`props:`,props.name)
props.name ='John'// try to change the value into 'John'

return (

<h1> Welcome {props.name}</h1>

We’ll have the same result as before that’s because the props are read-
only.

Functions as props
We know that props can hold any JavaScript data type, but what about
functions?
Of course, we can pass a function as props from parent to child. Actually,
this trick is used to pass data from child to parent. Don’t panic, we know
that React is a one way data flow, but in real life application, we are
obliged some time to get data from the child to the parent.
To make it possible, we take advantage of the function. Here is an
example of what we’re talking about.

App.js
const App = () => {

const alertMyInput = name => alert(name);

return (

<div>
<Welcome name="Sara" alertMyInput={alertMyInput} />

</div>

);

};

Welcome.js
const Welcome = props => {

console.log(`props:`, props.name);

return (

<button onClick={() => props.alertMyInput(`My name is James Brown


`)}>

ClickMe

</button>

);

};

Conclusion
We know it’s a lot of material to take in, but the key points we should
remember are:

 Props are arguments that are passed into React components.


 Props are used to ensure communication inside the component tree.
 Props are immutable as their value cannot be changed by the child
component.
 Props are only passed from parent to child.

Assessment: Quiz
After we run this code, what would be the result?
// Component Restaurant

const Restaurant = props => {


return <span>{props.food} </span>;
};

// The App component

const App = () => (


<div>
<Restaurant food="Sandwich" />
<Restaurant food="Pizza" />
<Restaurant food="Salad" />
</div>
)

Sandwich Pizza Salad PizzasaladSandwich Error


We can pass an object as a prop.

True False
Which type can’t be a prop?

Function String Array None of the above

Children prop
Children prop
Let's do a quick reminder of HTML. An HTML element is the combination of
an opening tag, a content and closing tag.
That approach is still valid using React. We can create a component and
pass or insert content between the opening and closing tags. That is what
we call React children.
const App = () => {

return (

<div>

<Welcome>Sarrah </Welcome>

</div>

);

};
Children prop usage
That is amazing, isn't it? The value passed between the two tags can be
used by the child component. Only the syntax has changed.
To access this value, we use props.children. Here is a much more detailed
example below :
const App = () => {

return (

<div>

<Welcome>Arya Stark</Welcome>

</div>

);

};

const Welcome = props => {

// whatever is passed between the tags of the component call can be


accessed via this syntax

return <h1>Welcome {props.children}</h1>;

};

When to use it?


The React documentation says that you can use props.children on
components that represent ‘generic boxes’ and that ‘don’t know their
children ahead of time’.
In simpler terms, we use it whenever we want to only display content.

Assessment: Quiz
To access the content of React children we use:

React.Children props.children props.Child_Name


To utilize a children prop, we use a self-closing tag so we can invoke the component.

True False
The children props can be only used with a special component.

True False

Style prop
Style prop
There are many ways to style React with CSS.
We will take a closer look at inline styling.

Inline Styling:
To style an element with the inline style attribute, the value must be a
JavaScript object:

camelCase Property Names:


Since the inline CSS is written in a JavaScript object, properties with two names,
like text-align, must be written with camel case syntax : textAlign.

Inline Styling
To style an element with the inline style attribute, the value of style
attribute must be a JavaScript object.
<div style={styleObject} > or <div style={{color: “red”, textAlign:
“center”}}>
Note: In JSX, JavaScript expressions are written inside curly braces, and
since JavaScript objects also use curly braces, the styling in the example
above is written inside two sets of curly braces {{}}.

Conclusion
One of the simplest way to add style to the component is with inline
styling. Therefore, it's best if we keep in mind that:

 The CSS rules are written in JavaScript, so we should change them


and follow the JavaScript standard (camel case, without spacing or
dashes).
 The style is written in an object so don’t forget the double curly
brackets.

Assessment: Quiz
The inline CSS is created as an object.

True False
The inline CSS is written with CSS language.

True False
To pass a style props we need to import a special package.

True False

Advanced
Rerendering on prop changes.
React components will render if the props change. React runs a
comparison between the new and previous Props and will automatically
render the new ones.
We have this simple React component that displays the title on screen :
import React from "react";

const MyComponent = ({ title }) => <h1>{title}</h1>;

export default MyComponent;

We are simply going to pass a title props to MyComponent component :

<MyComponent title="I'm learning React" />;

//output on screen: I'm learning React

Destructuring with props


In React, it's very common to pass multiple props to the component. So
it's no wonder that many of the React component functions interact with a
few or more props.

Let’s see an example:


Advantages of Destructuring
The advantages of ES6 destructuring assignment looks even cleaner in the
function component.

Applying the props destructuring technique allows us to write code like


this:
Solution
Reorder this code.
const Row = ({ name, age, email, doSomthingAmazing }) => {

return (

<div>

<span>name: {name}</span>

<span>age: {age}</span>

<span>email: {email}</span>

<button onClick={doSomthingAmazing}>Click !</button>

</div>

)}
Default props
Default props
As we have said in the beginning of this Super Skill, props are a
core idea in React's architecture.
Let's reflect on something for a moment. If we have used a prop
in a component but we forget to send its value from the parent
component, that will inherently produce problems in the
execution. For that reason, React provides a technique that will
enormously help us. That technique is called the Default
props.

Default props
This code defines a very simple ReactHeader component that renders
an <h1> element containing a heading for the documentation of a particular
React version.
// Simple React Component

function ReactHeader(props) {

return <h1>React {props.version} Documentation</h1>;

In the ReactHeader component, we are going to set the prop version to 16.
Everything else seems to be working properly in the ReactHeader
component.
//We are going to render ReactHeader with version=’16’

const App = () => { return <ReactHeader version=’16’ />}

//output on the screen :

//React 16 Documentation

What happens when the version prop is not passed?


You probably might have guessed it right. Here is what happens when the
ReactHeader component is rendered without the version prop:
// Simple React Component

function ReactHeader(props) {

return <h1>React {props.version} Documentation</h1>;


}

Since the version prop is not passed, the reference to props.version in the
component is undefined.
The output on the screen will be :
//output on the screen :

React undefined Documentation

Solution:
You could fix this by setting the default props in the component :
// Simple React Component

function ReactHeader(props) {

return <h1>React {props.version} Documentation</h1>;

// Set default props

ReactHeader.defaultProps = {

version: "16"

};

The component is going to use the default value for the version prop
whenever it is not passed.

Default props with destructuring


syntax
Alternatively, with the ES6 object destructuring syntax, you can
destructure the props of a functional component with default values.
// Simple React Component

function ReactHeader(props) {

// default value of version is 16

const { version = "16" } = props;

return <h1>React {version} Documentation</h1>;

}
//Or;

// default value of version is 16

function ReactHeader({ version = "16" }) {

return <h1>React {version} Documentation</h1>;

The component is going to use the default value for the version prop
whenever it is not passed.

Assessment: Quiz
The solution for not sending an expected props to a component is

Not using props at all Default props The props verification


We pass 15 to the ReactHeader props version, what is the output of ReactHeader ?

function ReactHeader(props) {
return <h1>React {props.version} Documentation</h1>;
}
ReactHeader.defaultProps = {
version: "16"
};

React 15 Documentation React undefined Documentation React 1516


Documentation
When we don't send a prop's value into the ReactHeader component, what will be the
displayed output?

function ReactHeader(props) {
return <h1>React {props.version} Documentation</h1>;
}
ReactHeader.defaultProps = {
version: "16"
};

React 15 Documentation React 16 Documentation React undefined Documentation

PropTypes
Prop Types
Props are a very important mechanism for passing read-only attributes to
React components. These attributes are usually required to be of a certain
type or form for them to be used properly in the component.

If a prop is passed to a component in a type or form that is unfamiliar, the


component may not behave as we intend it to. Thus, a great way of
improving React components is props validation.

propTypes:
React provides an internal mechanism for adding typechecking to
components. React components use a special property
named propTypes to set up typechecking.

PropTypes
When props are passed to a React component, they are checked against
the type definition configured in the propTypes property. When an invalid
value is passed for a prop, a warning is displayed on the JavaScript
console.

React.PropTypes:
Prior to React 15.5.0, a utility named PropTypes was available, as part of
the React package, which provided a lot of validators for configuring type
definitions for component props. It could be accessed
with React.PropTypes.

However, in later versions of React, this utility has been moved to a


separate package named prop-types, so you need to add it as a
dependency for your project in order to get access to
the PropTypes utility:
npm install prop-types --save-dev
It can be imported into your project files as follows:
import PropTypes from "prop-types";

You could use it as follows:


/** FUNCTIONAL COMPONENTS **/

function ReactComponent(props) {

// ...implement render logic here

ReactComponent.propTypes = {

// ...prop type definitions here

};

PropTypes validators:
As stated in the previous section, the PropTypes utility exports a lot of
validators for configuring type definitions. Here are the validators for the
basic data types:
PropTypes.any // PropTypes.bool // PropTypes.number // PropTypes.string //
PropTypes.func // PropTypes.array // PropTypes.object // PropTypes.symbol

Component.propTypes = {

anyProp: PropTypes.any,

booleanProp: PropTypes.bool,

numberProp: PropTypes.number,

stringProp: PropTypes.string,

functionProp: PropTypes.func

};

Multiple types:
PropTypes also export validators that can allow a limited set of values or
multiple sets of data types for a prop. Here they are:

 PropTypes.oneOf: The prop is limited to a specified set of values,


treating it like an enum.
 PropTypes.oneOfType: The prop should be one of a specified set
of types, behaving like a union of types.

Component.propTypes = {

enumProp: PropTypes.oneOf([true, false, 0, "Unknown"]),

unionProp: PropTypes.oneOfType([

PropType.bool,

PropType.number,

PropType.string,

PropType.instanceOf(Person)

])

};

Required props:
Oftentimes you need to control your component's output. You could do
that by conditional rendering.

You can prevent the component from rendering whenever a required prop
is not passed or is invalid by rendering an alternative output instead. That
is done by using the conditional rendering.
const SimpleComponent = ({ requiredProps }) => {

return (

<>

{requiredProps ? (

<h1>We need this {requiredProps} !</h1>

) : (

<h1>Ooops ! we need that props</h1>

)}

</>

);

};
We set an alternative for our output with requiredProps .

Assessment: Quiz
To add the propType package you need to run:

Nothing, it’s an internal package npm install prop-types --save-dev Npm i


prop-types
The prop type utility is added in react 18.1

True False
The prop type utility is only applicable on primitive data-type

True False

DOM Events
DOM Events
Let's take a trip to the past and remember DOM events:

 Events on a website are always interacting with the browser. For


example a mouse click, file loading on the browser or swiping the
image left or right.

Handling events with React elements is very similar to handling events on


DOM elements. There are some syntactic differences:

 React events are named using camelCase, rather than lowercase.


 With JSX you pass a function name as the event handler rather than
a string.

We can find many events such as onMouseMove, onChange,


onClick and many more.

Events/Functions
Since we are writing JavaScript, React events are written in camelCase
syntax:
onClick instead of onclick.
React event handlers are written inside curly braces:
onClick={handleClick}
const ActionLink = () => {

const handleClick = e => {


e.preventDefault();

console.log("The link was clicked.");

};

return (

<a href="/" onClick={handleClick}>

Click me

</a>

);

};

Events/ Functions
In the example above, the onClick attribute is our event handler, and it is
added to the target element in order to assign the function to be executed
when that element is clicked. The onClick attribute is set to the
handleClick function, which sends an alert message.
In simpler terms, this means that whenever the button is clicked on, the
handleClick function is called which displays the alert box.

Events/ Functions props


There are many situations when you're writing with React and you’ll want
to pass a function as a prop.
Usually it’s to pass down to a child component so that the child can notify
the parent of an event.
In this example, we have passed handleClick function from ActionLink
component as props to ActionComponent.
We wait from ActionComponent to trigger an action , in this case it's an
alert message.

Events/ Functions props test

In ActionComponent, what we expect when we click the Click Me! Link is to


send an alert message from handleClick which is defined inside the parent
component ActionLink.

Events/ Functions props test

As we had expected, the alert gets triggered and the test is successfully passed!

Events/ Conclusion
Handling events is a very important aspect to learn.
Since applications are based on user interactions, handling gives us the
power to control any interaction that happens between the user and our
application.
React puts forward all the DOM events handlers that exist only with a little
difference in the way we call them (the use of the camel case naming.)

Assessment: Quiz
Is this a valid statement?

onSubmit={handleSubmit}

True False
The event handler can only be applied on a button

True False
e.preventDefault(); is used to change the default behaviour of a form.

True False

Conclusion
React Props RECAP
Using the component-based architecture can make our life easier as a
developer, but rendering static content is not the point here. React solves
this problem by using the props solution. So we can now say that props
are at the center of React's ecosystem.

Making the props navigate in a unidirectional way makes the debugging


process very easy in React applications. Another advantage is that the
props' value can’t be modified or deleted by the child, it makes it safer to
pass data from parent to child.

To make sure that this approach works in the best way, React offers the
module propTypes that can be used to make sure the data you receive is
valid.

React State
React State: Overview
Introduction
While developing applications with React, you have two ways for holding
data:

1. The React props that we have encountered previously.


2. The component state that we will see in this super skill.

In this super skill, we are going to learn:

 What is state?
 How to use state in React?
 What is a component lifecycle?

What is a state?
State is a Javascript object that stores a component's dynamic data and
determines the components' behavior. Because state is dynamic, It
enables a component to keep track of changing information, whilst
rendering, in order for it to be more dynamic and interactive.

Why use state?


In fact, React virtual DOM doesn't allow any random modifications to the
data. We need to initialize and then modify the data in State, so it's as if
we are describing the scenario for React then the application will take care
of any changes.

React, previous to the 16.8 version, was using the class-based component
to handle the stateful component. After this major update, the React core
team gave us the ability to handle state even in a functional component
using the react hooks.

How to use State?


First, let’s take a look at State before the 16.8 version. As we've said
earlier, the state was only used in a class-based component. So to define a
state in a class, you can just follow the example below :
import React from "react";

class Welcome extends React.Component {

state = {

name: "Sara"

};

render() {
return <h1>hello {this.state.name}</h1>;

export default Welcome;

A state is a Javascript object that can contain any type of data.

How to use State?


A state must be kept as simple as possible. It can be set only by using
the setState() method and calling this method triggers UI updates.
The state represents the local state of the component. It can only be
accessed or modified inside the component.
class Welcome extends React.Component {

state = {

name: "Sara"

};

handleClick=()=>this.setState({name:'Arya'})

render() {

return(

<>

<h1>Hello {this.state.name}</h1>

<button onClick={this.handleClick}> ClickMe</button>

</>

Assessment: Quiz
The state value can be changed directly by assigning values

True False
React merges the object you provide into the current state using

setState() State()
The setState method in React triggers the UI rendering
True False

Using Hooks
Using Hooks
After the version 16 (using Hooks), in our case, we will use Hooks to be
able to control our state inside the component. So let's go over these
Hooks.

Hooks were recently introduced to React in February 2019 and it's a


revolutionary feature. This concept tends to change the way we write code
in a certain component of our application.

Hooks have been considered as a potential solution for problems in React


Applications thanks to its simplicity and its new functionalities .
Now, we can access the state even in the Functional Component.

PS.We will study React Hooks in detail in the next skills. We have just
used useState in this skill.

Let's start:
We will use this component to introduce Hooks as we will further analyze
it:
const MyFunctionComponent = () => {

// setting the state hooks

const [name, setName] = useState("Arya Stark");

return (

<div>

<p>hello my name is {name}</p>

</div>

);

};

To explain the code, first we have declared a state variable then we have
stored a name with the value of "Arya Stark" and finally, we have
accessed our component to display the name.

Assessment: Quiz
To manage a state in a component we use

setState() useState() None of the above


Hooks are implemented since React's first released version

True False
Consider the following code. Which variable holds the method to change the state?

const [family,setFamily] = useState('Stark')

family setFamily

Life Cycle
LifeCycle
Every React Component has a lifecycle of its own.
A component lifecycle can be defined as the series of methods that are
invoked in different stages of the component’s existence.

A React Component can go through three life stages.


Each component in React has a lifecycle which we can monitor and
manipulate during its three main phases.

The three phases are:

1. Mounting: The first phase of the component lifecycle is when the


elements are put in the DOM.
2. Updating: The second phase in the lifecycle is when a component
gets updated.
3. Unmounting: The final phase in the lifecycle is when a component
gets removed from the DOM.

Mounting
This phase is the first phase of the component lifecycle. It contains four
methods that are invoked in this order, when an instance of a component
is being created and inserted into the DOM:

1. Constructor(): This method is called when the component is initiated.


The constructor method is the place where we declare the state and
pass the props as arguments.
2. getDerivedStateFromProps(): This method is called before rendering
the elements in the DOM. getDerivedStateFromProps exists for only
one purpose. It enables a component to update its internal state as
the result of changes in props.
3. render(): This method is the only required method when working
with classes. It examines the props and the states and returns the
element to render.
4. ComponentDidMount(): This method is invoked immediately after the
component gets rendered and it’s the perfect place to call the
setState method.

Updating
When the state or the props get updated, the component enters this phase
of its lifecycle. This phase contains five methods invoked in this order:

1. getDerivedStateFromProps(): This method is the same as the one in the


mounting phase. It returns an object to update the state or returns
null if there is no update.
2. shouldComponentUpdate(): This method is the second method to invoke
in this phase. It will either define the component that will be updated
or not, depending on whether or not the props or the state get
modified.
3. render(): The same as the one in the mounting phase, except it will
re-render according to the new props/state.
4. getSnapshotBeforeUpdate(): This method is invoked right before the
most recently rendered element is committed. It gives us the
possibility of capturing some information from the DOM, before it
potentially changes.
5. componentDidUpdate(): this method is called immediately after the
update occurs.

Unmounting
The component enters this phase at the end of its life, meaning that it will
be removed from the DOM.

1. componentWillUnmount(): This method is called immediately before the


component's end of its lifecycle. It’s the perfect place to clean up our
component.

Let's recap!
Let’s sum up what we have seen, the component passes through three
major phases during its lifecyle. Each phase contains methods to be
invoked in a certain order. In some cases we need to change the behavior
of these methods in order to accomplish specific tasks.
In the image below, there is a visual description of these phases.
Assessment: Quiz
Which React Component method is called after the component is rendered for the
first time?

componentDidUpdate componentDidMount componentWillMount comp


onentWillUnmount():
Which React Component method should you override to stop the component from
updating?

componentDidUpdate componentDidMount
The first lifecycle that gets executed is a

constructor componentWillMount componentDidMount

Conclusion
React State Recap!
By the end of this super skill, we have learned that State is crucial when
dealing with React Component. After the 16.8 version of React JS, we are
now able to use the state object in both functional and class-based
component. Manipulating state was tricky when it came to dealing with
complex projects, that’s why the React community and other developers
came up with efficient and practical solutions.
React Hooks
React Hooks: Overview
Introduction to React Hooks
The React 16.8 update was a major revolution in the way that React treats
and interacts with components and this all thanks to hooks.

Hooks is making big waves in the React community because it reduces the
complexity of state management.
In this skill, we are going to see:

 What are React Hooks?


 What is useState hook?
 What is useEffect hook?
 What is useRef hook?
 How to make your own custom hooks?

useState
While describing the use of state in the previous Super Skill, we have seen
that the state can only be updated using the this.setState method.
The state is characterized by two major things: a value (aka getter) and a
method to set this value (aka setter).

The same logic still stands with the useState() method.

Declaring a state variable:


First of all, we need to learn how to declare a state variable in our
component:

1. Import the hook useState.


2. Declare your state variable in an array (the getter and the setter)
3. Initialize your state variable with useState( ).
This example will help you understand more:

import React, { useState } from "react";


Accessing The State
Now that we have already declared our component state, we need to be
able to access the value of that state.
Like any other variable in JavaScript, if we want the value of a state, we
invoke the state’s name like it's shown in the example below:
import React, { useState } from "react";

const MyFunctionComponent = props => {

// setting the state hooks

const [name, setName] = useState("Arya Stark");

return (

<div>

{/* here we use the getter to get the state value */}

<p>hello my name is {name}</p>

</div>

);

};
Set the state's value:
To change the state's value, we have to use the setter that we
implemented in the state declaration. In this example, the setName
method acts as the setter (or the modifier):
const MyFunctionComponent = props => {

// declaring the state hooks

const [name, setName] = useState("Arya Stark");

// here we use the setter to change the content of the name state

const handleClick = () => setName('Tyron Lanyster')

return (

<div>

{/* here we use the getter to get the state value */}

<p>hello my name is {name}</p>

<button onClick={handleClick}>Click if you want to give the crown


to Tyron Lanyster</button>

</div>

);

};

Keypoints to keep in mind:


Now that we know what the useState() Hook does and once we our
component initial state, we need to be able to access the value of that
state.
Like any other variable in JavaScript, if we want the value of a state, all we
have to do is invoke the state’s name, like shown in the example below:
import React, { useState } from "react";

function Welcome() {

const [name, setName] = useState(“Jane”)

return (

<div>
<h1> Welcome {name} </h1>

</div>

export default Welcome;

Output:

Assessment: Quiz
In this case, counter is :

const [counter,setCounter] = useState(0);

getter setter
What is the initial value of the state?

const [counter,setCounter] = useState(5)

2 5 1
the setter is:

A function that changes the value of the state variable. A function that calls
the state variable inside the component. A function that sets the state's value by
default.
Use Effect
useEffect
The useEffect() method takes:
A function as the first parameter that describes the effect we want to
apply. Then, it takes an array as a second parameter that will determine
when this effect should appear or disappear.

So keep in mind that to start up, we need to use an empty array [ ] as a


second parameter. However, this parameter remains optional.
[] means the effect doesn’t use any value that participates in React's data
flow and that's the reason why it is considered safe to apply it once.
It is also considered a common source of bugs when the value is actually
being used.

This code will better illustrate what we have mentioned:


// setting the useEffect to trigger while the component is been
rendering

useEffect(()=>{

alert(`hello this a message`)

},[])

useEffect
The useEffect() method allows component functions to manage side
effects.
It plays the same role as componentDidMount(), componentDidUpdate(),
and componentWillUnmount() in React classes only it is implemented through
a single API.
Assessment: Quiz
When does the component execute the useEffect method?

With every state modification. Only when it's first rendered. When this
component is destroyed.
Will it work if we remove the dependency array [ ] argument from the useEffect
function?

True False
In order to use a spinner, what should we add as a secondary parameter inside the
useEffect method?

[] {} ()

Common mistakes
useRef()
The useRef() Hook is a function that returns a mutable reference object
whose current property is initialized to the passed argument (initialValue).
The returned object will persist for the component's entire lifetime.

This example may help you:


function App() {

let [name, setName] = useState("Ned stark");

// we declare the input inside the variable


let nameRef = useRef();

// we are referring to input to change the value

const submitButton = () => {

setName(nameRef.current.value);

};

return (

<div className="App">

<p>{name}</p>

<h1>Who is your favorite Games of throne character</h1>

<div>

<input

placehoder="enter your preferred GOT character..."

ref={nameRef}

type="text"

/>

<button type="button" onClick={submitButton}>

Submit

</button>

</div>

</div>

);

In this function we are recovering the input value using the useRef method
instead of onChange event. That may be a potential bug event if works for
now. A ref created with useRef will be created only when the component
has been mounted. Refs can be used for accessing DOM nodes or React
elements, and for keeping mutable variables.
Destructuring using object:
Don't forget: hooks use arrays to store data.
As we have previously mentioned, Hooks are applied in an array:
const { state, setState} = useState("intial state")

If we perform destructuring using the curly brackets, we’ll receive this


error:

Reminder that this code is incorrect. We need to use brackets and not
curly braces.
const [state, setState] = useState("intialState)

Hooks inside a condition:


We should avoid creating the state hook in a condition because that will
violate the hook rules. Once you break these rules, this error will occur:
import React, { useState } from 'react'

const Welcome = props =>{

if(props.name==='ned stark'){

const [bgColor,setBgColor ]= useState('white')

else{

const [bgColor, setBgColor] = useState('black')

return (

<h1 style={{backgroundColor:{bgColor}}} >{props.name}</h1>

}
export default Welcome

Output

Hooks inside a loop:


Another common mistake is to use the hook inside loops. Here is an
example to illustrate the error.
function App() {

for (let i = 1; i < 5; i++) {

const [state, setstate] = useState(i);

return (

<div>

<h1>{state}</h1>

</div>

);

export default App;

Output

Nesting before using the state:


We can't nest inside a function before using our state.
function App({ date }) {

function updateCount(byValue) {
const [currentDate, setCurrentDate] = useState(new Date());

const [count, setCount] = useState(0);

setCount(count + byValue);

setCurrentDate(new Date());

function formatDate() {

const hour = currentDate.getHours();

const minute = currentDate.getMinutes();

const second = currentDate.getSeconds();

return `${hour}:${minute}:${second}`;

const prettyDate = formatDate();

return (

<div className="App">

<h2>

You clicked {count} times, last time at {prettyDate}!

</h2>

<button onClick={() => updateCount(-1)}>Decrement</button>

<button onClick={() => updateCount(1)}>Increment</button>

</div>

);

useState inside an effect:


Now, we will go through some points where we invoke the useEffect.
Important notice: The combined use of both the useState and useEffect
generates an infinite loop.
So, don’t call a useState inside a useEffect.

Let's Sum Up!


To summarize, we can only call Hooks at the top level.
We should be aware of these rules:

 Don't declare hooks in if statements.


 Don't declare hooks in loops.
 Don't declare hooks in nested function.
 Always make sure to use the brackets instead of the curly brackets.

Assessment: Quiz
We can't apply useEffect

inside a useState. in a (if/else statement) condition. in a sub-funciton.


All answers are correct.
Is the following code correct?

const {name, setName}= useState()

True False
We can invoke a useState() in a useEffect() hook.

True False

Creating Custom Hooks


Custom Hooks.
A custom Hook is a JavaScript function whose name begins with "use". It
provides flexible logic sharing.
We can call other Hooks in our custom Hooks.
Before we start, We need to be able to build our own Hooks in a
personalized way and it will still ensure the functional reusability.
The following example of users and posts will help us better understand
custom Hooks' practicality.
Custom hooks are simply a wrapper function surrounding our existing hooks.
That's all there is to it! The only catch is: in order for React to recognize a
function as a custom hook, its name should always start with use so that you can
tell at a glance that the rules of Hooks apply to it.

Create a custom Hook


We will create a useInterval Hook and then we will use it.
function useInterval (timeout, getValue) {

const [value, setValue] = useState(getValue);

useEffect(() => {

const intervalID = setInterval(

() => setValue(getValue()),

timeout

);

return function () {

clearInterval(intervalId);
}

}, []);

return value;

const get CurrentDate = () => new Date();

function App() {

const date = useInterval(1000, getCurrentDate);

return <p>Nous sommes le {date.toLocaleString(“fr-FR”)}</p>;

Assessment: Quiz
A custom Hook is a JavaScript function.

True False
We can invoke a custom Hook in a conditional statement.

True False
A custom Hook is a function that provides flexible code.

True False

Conclusion
Tips:
 Avoid declaring useState, useEffect or custom Hooks:
o In a loop.
o In a condition.
o In a nested function.
 Don't forget array destructuring.
 You should use custom Hooks with components that have the same
functionality.
 Avoid applying useRef to DOM elementS.

Let’s recap:
Hooks is a new feature that has been introduced to React in order to make
dynamic data manipulation easier.
useState is essential for selecting a default state value then updating it.
Time to put into practice what we have been learning!

You might also like