Mastering React Components

ark7

M.Ark

Posted on June 12, 2024

Mastering React Components

React components are the fundamental building blocks of a React application.
React components are reusable, self-contained pieces of code that define how a portion of the user interface (UI) should appear and behave.

The beauty of React is that it allows you to break a UI (User Interface) down into independent reusable chunks, which we will refer to as components. The following picture should give you an idea of how to do that when building a very basic app.

Image description
For example, this website could be broken into the following components:

  • App, which represents your main application and will be the parent of all other components.
  • Navbar, which will be the navigation bar.
  • MainArticle, which will be the component that renders your main content.
  • NewsletterForm, which is a form that lets a user input their email to receive the weekly newsletter.

Components can be thought of as custom HTML elements that React uses to build the UI.
React breaks down its components into two types. I.e functional components and class components.
We are going to discuss each one of them one by one.

Functional components

Functional components are JavaScript functions that accept props(properties) as arguments and return React elements (JSX).
Functional components do not have their own state or lifecycle methods, but with the introduction of hooks in React 16.8, functional components can now manage state and side effects.
Here is an example of a functional requirement using props.

Image description

Class Components:

Class Components are ES6 classes that extend React.Component and must define a render method that returns React elements.
Class components can have their own state and lifecycle methods, making them more powerful than functional components (prior to hooks).

Here is an example:

Image description

React components key concepts:

1. JSX:
JSX is a syntax extension for JavaScript that looks similar to HTML and is used to describe the UI.
React components typically return JSX to define what the UI should look like.
Here is a JSX sample:

Image description

2. Props:
Props (short for properties) are read-only inputs to components. They are used to pass data from parent components to child components.
Here is a sample:

Image description

3. State:
State is a built-in object in class components (or managed via hooks in functional components) that holds data that may change over the component's lifetime.

State changes can trigger re-renders of the component.
Here is an example:

Image description

This bring us to the end of our discussion on React components.

You can follow me on GitHub: https://github.com/kibetamos

Happy hacking!

💖 💪 🙅 🚩
ark7
M.Ark

Posted on June 12, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related