ReactComponents EtPlus
ReactComponents EtPlus
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.
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.
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.
render(){
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.
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";
Assessment: Quiz
What are the types of React components?
stateless statefull
After which version, we can only use functional components:
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:
return (
<>
</>
);
};
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.
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 (
<>
</>
);
};
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";
return (
<>
</>
);
};
return (
<>
</>
);
};
Reusability is important.
Using components
Using a Component
After creating our first component, it’s time to use it.
MyFirstComponent.js
import React from "react";
const MyFirstComponent = () => {
};
App.js
import React from "react";
<>
<MyFirstComponent />
</>
);
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>
<Footer />
// Footer Component
</div>
);
};
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.
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";
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 = () => {
// WRONG!
return (
<Comp1 />
<Comp2 />
<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.
<React.Fragment>
<div />
<div />
</React.Fragment>
);
return (
<>
<div />
<div />
</>
);
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.
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?
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.
JS example
Here is another example to consolidate what we were just talking about.
function Greeting(name) {
React example
Now let’s try the same idea with a React component.
function Greeter(props) {
return (
<div>
<Greeter name="I am the King" /> {/* 💥 "I am the King" is the prop
value*/}
</div>
);
};
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) {
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?
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" />;
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
return (
<h1>
`Hello`
</h1>
)
App.js
const App = () => (
<div>
</div>
);
Welcome.js
const Welcome = props =>{
console.log(`props:`,props)
return (
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 (
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 (
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 = () => {
return (
<div>
<Welcome name="Sara" alertMyInput={alertMyInput} />
</div>
);
};
Welcome.js
const Welcome = props => {
console.log(`props:`, props.name);
return (
ClickMe
</button>
);
};
Conclusion
We know it’s a lot of material to take in, but the key points we should
remember are:
Assessment: Quiz
After we run this code, what would be the result?
// Component Restaurant
True False
Which type can’t be a prop?
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>
);
};
};
Assessment: Quiz
To access the content of React children we use:
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:
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:
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";
return (
<div>
<span>name: {name}</span>
<span>age: {age}</span>
<span>email: {email}</span>
</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) {
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’
//React 16 Documentation
function ReactHeader(props) {
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 :
Solution:
You could fix this by setting the default props in the component :
// Simple React Component
function ReactHeader(props) {
ReactHeader.defaultProps = {
version: "16"
};
The component is going to use the default value for the version prop
whenever it is not passed.
function ReactHeader(props) {
}
//Or;
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
function ReactHeader(props) {
return <h1>React {props.version} Documentation</h1>;
}
ReactHeader.defaultProps = {
version: "16"
};
function ReactHeader(props) {
return <h1>React {props.version} Documentation</h1>;
}
ReactHeader.defaultProps = {
version: "16"
};
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.
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.
function ReactComponent(props) {
ReactComponent.propTypes = {
};
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:
Component.propTypes = {
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 ? (
) : (
)}
</>
);
};
We set an alternative for our output with requiredProps .
Assessment: Quiz
To add the propType package you need to run:
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/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 = () => {
};
return (
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.
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.
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:
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.
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.
state = {
name: "Sara"
};
render() {
return <h1>hello {this.state.name}</h1>;
state = {
name: "Sara"
};
handleClick=()=>this.setState({name:'Arya'})
render() {
return(
<>
<h1>Hello {this.state.name}</h1>
</>
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.
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 = () => {
return (
<div>
</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
True False
Consider the following code. Which variable holds the method to change the state?
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.
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:
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:
Unmounting
The component enters this phase at the end of its life, meaning that it will
be removed from the DOM.
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
The first lifecycle that gets executed is a
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:
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).
return (
<div>
{/* here we use the getter to get the state value */}
</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 => {
// here we use the setter to change the content of the name state
return (
<div>
{/* here we use the getter to get the state value */}
</div>
);
};
function Welcome() {
return (
<div>
<h1> Welcome {name} </h1>
</div>
Output:
Assessment: Quiz
In this case, counter is :
getter setter
What is the initial value of the state?
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.
useEffect(()=>{
},[])
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.
setName(nameRef.current.value);
};
return (
<div className="App">
<p>{name}</p>
<div>
<input
ref={nameRef}
type="text"
/>
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")
Reminder that this code is incorrect. We need to use brackets and not
curly braces.
const [state, setState] = useState("intialState)
if(props.name==='ned stark'){
else{
return (
}
export default Welcome
Output
return (
<div>
<h1>{state}</h1>
</div>
);
Output
function updateCount(byValue) {
const [currentDate, setCurrentDate] = useState(new Date());
setCount(count + byValue);
setCurrentDate(new Date());
function formatDate() {
return `${hour}:${minute}:${second}`;
return (
<div className="App">
<h2>
</h2>
</div>
);
Assessment: Quiz
We can't apply useEffect
True False
We can invoke a useState() in a useEffect() hook.
True False
useEffect(() => {
() => setValue(getValue()),
timeout
);
return function () {
clearInterval(intervalId);
}
}, []);
return value;
function App() {
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!