React Components Tutorial

In this React Components tutorial, we'll explore React components and how to use them in HTML.

What are React Components?

  1. React components are reusable UI building blocks.
  2. They can be stateful(Class Components) or stateless(Functional Components).
  3. Components can be used to create complex UI structures.

What are the Functional Components?

  1. The Functional components are simple JavaScript Functions.
  2. They are stateless, meaning that they do not have any internal state.
  3. Functional components are typically used to render simple UI elements, such as buttons, headings, and lists.
function MyHeading(){
    return <h1>This is an Heading!</h1>
}

We can render the functional components as simple as we did for JSX.

root.render(<Myheading />);

In the previous tutorial we said we can render multiple elements. Like this

function Profile(){
    return (
        <>
        <h1>My Profile</h1>
        <p>I'm a Front End Developer</p>
        <h3>My Skills</h3>
        <ul>
                <li>React</li>
                <li>Bootstrap</li>
                <li>CSS</li>
        </ul>
        </>
    )
}


Render the above code and start the development server and you will notice the changes in your browser

Props

  1. Props in React are a way to pass data from one component to another.
  2. They are read-only values that are passed to a component as an object.
  3. Props can be any JavaScript value, including strings, numbers, objects, arrays, and functions.
function Button(props) {
    return <button>{props.text}</button>;
  }
  

To use the Button component, you would simply call it with the desired props

<Button text="Click Here" />

You can also destructure props in functional components. This allows you to extract specific props from the props object and assign them to variables.

export function Button({ text }) {
    return <button>{text}</button>;
  }
  

This code is equivalent to the previous code, but it is more easy and readable.

Let's see another example

function Profile({name, message}){
    return (
        <>
            <h1>Hello, {name}</h1>
            <p>{message}</p>
        
    )

}

const profile = <Profile name="Ben" message=""Welcome back! />;
const container = document.getElementById("root");
const root = ReactDOM.createRoot(container);

root.render(profile)

React Class Components (stateful components)

  1. React class components are a type of React component that is written as a class.
  2. They can have state and lifecycle methods, which makes them more complex than functional components.
  3. Class components are typically used to render complex UI elements, such as forms, tables, and modals.
  4. They can have state, which allows them to track and update data.

    The state in class components is used to store and manage the data that can change over time and influence the component's behaviour and rendering.

    You should use class components when you need to render a complex UI element that has state or lifecycle methods.

    For example, you might use a class component to render a form that allows users to enter and submit data.

import React from "react";
    import ReactDOM from "react-dom/client";
    
    class Button extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          text: "Click Me!",
        };
      }
    
      handleClick() {
        this.setState({
          text: "You clicked me!",
        });
      }
    
      render() {
        return (
          <button onClick={() => this.handleClick()}>{this.state.text}</button>
        );
      }
    }
const container = document.getElementById("root");
const root = ReactDOM.createRoot(container);
root.render(<Button />);
    
  

Exporting and Importing the components

  1. Exporting and importing components in React allows you to create modular, reusable code by breaking down your application into separate components.

In your component file, define your component as a JavaScript function or class. For example:

// Header.js
import React from 'react';

function Header() {
    return <h1>My App Header</h1>;
}

export default Header;

You can export your component using export default. This allows you to import it using any name when importing it in another file.

In another file where you want to use the component, import it using import

import React from 'react';
import Header from './Header'; // Import the Header component from Header.js

function App() {
    return (
    <div>
        <Header />
        {/* Other components or content */}
        </div>
    );
}

export default App;
    
  1. You use import to bring in the component you want to use. The relative path ./Header is used to locate the Header component file.
  2. The imported component can be used within the importing file as if it were any other JavaScript function or class.
  3. The imported component can be used within JSX by enclosing it in angle brackets, such as <Header />.

Nesting the components

  1. Nesting functional components in React is a common way to create complex user interfaces
  2. It allows you to break down your UI into smaller, more reusable pieces, which can make your code easier to maintain and update.

You can create functional components using JavaScript functions. Each component typically returns JSX to describe what should be rendered. Here's an example of two simple functional components

function Header() {
    return <h1>My App Header</h1>;
  }
  
  function Content() {
    return <p>This is the content of my app.</p>;
  }
  

You can nest components by including one component within another as you would include any other JSX element. For instance, you can include the Header and Content components within a parent component like App

function App() {
    return (
        <div>
            <Header />
            <Content />
        </div>
    );
  }
  

To render the root component (in this case, App), you can use ReactDOM.render() in your entry point file (usually index.js):

import React from 'react';
import ReactDOM from 'react-dom/client';
    
function App() {
    return (
    <div>
        <Header />
        <Content />
    </div>
    );
}
const container = document.getElementById("root");
const root = ReactDOM.createRoot(container);

root.render(<App />);
    

You can pass data or properties (props) from a parent component to a child component to make your components more dynamic.

function UserInfo(props) {
return 

{props.name} - {props.age} years old</p>; } function App() { return ( <div> <Header /> <Content /> <UserInfo name="Alice" age={30} /> </div> ); }