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

React Components

A component is a reusable piece of code that returns a React element and can accept input properties. There are two types of components in React: class components and functional components. After React version 16.8, the preferred approach is to use functional components, which are simpler and can now hold state. Components are the building blocks of a React application and can be composed together to display portions of the user interface.

Uploaded by

Yesmine Makkes
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

React Components

A component is a reusable piece of code that returns a React element and can accept input properties. There are two types of components in React: class components and functional components. After React version 16.8, the preferred approach is to use functional components, which are simpler and can now hold state. Components are the building blocks of a React application and can be composed together to display portions of the user interface.

Uploaded by

Yesmine Makkes
Copyright
© © All Rights Reserved
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 8

What’s Component?

First thing first, before we start off by defining the react component, let’s take a look at the
component definition.
By a simple research on Google, we can find a lot of complicated definitions.
But let’s have an easier one; A component is a piece of code, that can be reusable and cooperate
with other component to create a UI.
Well, let’s see the image below, and how it is structured :

Benefits of using components


Working with component makes the web development much easier. The reasons are :

• Reusability
Every implemented component can (if we don’t must) be reused while building our web
application.
Let’s take the example of a sidebar of a dashboard, it will be used whatever the page we display.

• Maintainability
Every component is implemented separately from the others so it can be maintained separately
without affecting other UI composition.

• Platform independency
In reality, the web component are build using HTML, CSS and JavaScript which make it a cross
platform.

• Scoop privacy
Since every component is built to be working alone that make its content more private than shared
code.

What's React Component?


Components are the building blocks of any React app. Notice that a typical React app will have
many of these.
Simply put, a component is a JavaScript class or function that optionally accepts inputs i.e.
properties(props) and returns a React element that describes how a section of the UI (User
Interface) should appear.
// 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!”
A component is an external library used by react False
The component is a set of code that generate a specific UI True
Component is a JavaScript approach onlyTrue

Types of components
As we said earlier, there are two types in react component, basically that division was before React
version 16.8.
But for the learning purpose we should know it.
The two types of react component are:
• Class based component: referring to JavaScript classes.
• Functional based component: referring to JavaScript function.

Class based component


If you read articles on the Internet about react component, you will find the following nomination
that refer to class-based component:
• Smart component
Before React 16.8, the logic was only implemented in this type of component, because of the
advantage that classes gives over functions.
• Stateful component
Before february 2019, only class can hold and manage JavaScript State.
• Container
It’s called so because usually it hold/contain numerous other (mostly functional)
components.
Enough talking, let’s take a look at an example:
class Greeting extends React.Component {
render(){
return <h1>Hi, I’m a smart component!</h1>;
}
}

Functional based component


These components are purely presentational and are simply represented by a function. This
functions 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
literature. 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, it’s 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;

What is the types of React components? class function


The functional component is stateless
After which version, we can use only functional based component16.8

Create our first component


After all that talk about component, 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 return JSX, that’s all we need to create a component.
Using the JavaScript power, we can manipulate these functions as we wish. We are going to create
the component Greeting from 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;

What should we remember?


There are few things that you should notice about that first example, the first one is the import
React from "react"; well it’s a mandatory thing since we work with JSX and the export
default App; this is also a mandatory act that must me performed. We’ll explain its necessity.
Remember the module of ES6, and how it’s make our life much easier as a developper. Well it’s
time to get advantage of it.
In order to separate the component from each other, we can use the JavaScript modularity to do so.
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 uppercase letter that’s
also a necessity in order to not confuse it with simple HTML tags
Default export
As JavaScript file, we can export our component as the example below 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 by default the component
MyFirstComponent

Named exports
The other way to export a component is the named export, let’s take a look at the example.
This 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>
</>
);
};

Creating component best practices.


After creating our first component, here is a list of some commun best practices that we should
know:
• Keep components small and function-specific:
• Function-specific components can be standalone, which makes testing and
maintenance easier.
• Each small component can be reused across multiple projects.
• With smaller components, it’s easier to implement performance optimizations.
• It’s easier to update smaller components.
• 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 all in a single folder:
Keep all files relating to a component in a single folder, including styling files.
• Reusability is important:
import
React
from
'react'
const
Car = () => {
return
<h2>Hi, I am a Car!</h2>; }

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 first import it.
Well, let’s see an example to make it clear.

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;

Using a Component
Wouhou! Here, we start making things.
As we can see, we get the component MyFirstComponent inside the App. We may ask the App isn’t
a also a component. 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? Well that method lives
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);

Notice that, applications built with React have a single root DOM node
Application built with React have many root False
A component can render another component True
To establish a parent child relationship, a component A should render a component B True

What's HOC?
We have seen the higher order function in JavaScript, which is a function that accept a function as a
parameter.
Well, React clone that functionality with component so it gives us the possibility to create a Higher
Order Component which is a component that accept a component as a parameter.

Concretely, a higher-order component is a function that takes a component and


returns a

Why HOC?
In software development one of the commonly talked about principle is “Don’t Repeat YourSelf”
aka. DRY. Creating a simple utility function, that is used across several parts of the codebase is
something you may have done frequently. You are essentially following DRY by doing so. You are
reusing the same utility function, without repeating the code.
In React, one of the ways to achieve DRY across components, is to use the Higher Order
Component (HOC) concept. We can share common functionality without repeating code.
Example of HOC
In this example, we will add a waiting message on the wrapped component. Don’t be afraid of the
weird code we'll understand it 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;
};

A HOC is a component that use another component False


A HOC is a component accept as parameter another component True
A HOC can only be a class based component False

Returning multiple nodes


Since the component is only a JavaScript function, and we know that JavaScript functions can only
return one thing, so the component can only return one JSX element.
Hearing that, can sound confusing, but here is how to do it.
We wrap all the element we want in a single element div or section or whatever wrapper we choose.
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
As we know the div or section or any other html container have already a default css properties
that could affect our design.
To escape this default properties, React gives us the React.Fragment which is a wrapper that have
no effect to the css. A React fragment cannot be styled
Take a look at its syntax in the example below
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 many problems when you try to
reuse the component.
⇒ So, we advise to use the relative paths instead.
//relative path
import MyFirstComponent from "./MyFirstComponent";
//absolute path
import MyFirstComponent from '/src/component/MyFirstComponent'

Can we return multiple node in the function return false


React fragment can be styled False
Using absolute path can gender path conflict. True

You might also like