Page Content

Tutorials

What Are The React Components With Code Example

React Components

React Components
React Components

As separate, reusable functional units that define user interface (UI) elements, React components are the essential building blocks of any React.js application. React apps are built by putting together a number of components, each of which is in charge of rendering a little, independent section of HTML.

The reason for React’s success is its method of creating user interfaces, which emphasises:

Composability: Nesting components allows simpler units to be integrated into more complex applications. Modularity simplifies user interfaces (UIs) by separating code sections so they don’t interact.

Declarative nature: Instead of explaining how to alter a state, React enables developers to specify how the user interface should appear in that state. The underlying HTML DOM is then effectively updated by React to match the stated user interface.

Efficiency: React uses an in-memory VDOM to simulate the HTML DOM. When component data changes, React updates the Virtual DOM and swiftly compares the old and new DOMs (diff method). Change only the essential DOM elements in the real DOM rather than refreshing the entire document for faster updates and improved performance.

Unidirectional Data Flow: One-way data flow is implemented by React, mostly through “props,” which facilitates the understanding and upkeep of apps.

Defining Components

React offers two main methods for defining custom components: Class Components and Functional Components.

Class Components

Class Elements ES6 classes that extend React.Component are called class components. Because they can employ lifecycle methods and maintain internal state, they are referred to as “stateful” components. Although many developers now use Hooks to create functional components, class-based components were once the most common technique to generate React components. Class components, which are present in legacy code and offer a concise introduction to ideas like state management, are still crucial to comprehend.

Key aspects of Class Components:

Render() method: To specify how the component renders to the DOM, a basic class component needs to declare a render() method. React nodes, which are frequently defined using JSX syntax, are returned by this method.

Constructor(): The constructor method is commonly used in class components to bind event handlers and initialise internal state. The constructor’s initial statement needs to contain the super(props) call.

This.state: State is a unique React class attribute that controls page rendering. React automatically re-renders components with state changes. Start the state object with constructor.

This.props: This.props is a basic React object that class components use to access properties that have been given from a parent component. By acting as arguments given to a JSX element, these “props,” which stand for properties, enable unidirectional data and method flow from a parent component to its child components..

Code Example (Class Component):

import React, { Component } from 'react';
class IceCreamCart extends Component {
  state = {
    count: 0
  };
  addIceCream = () => {
    this.setState({ count: this.state.count + 1 });
  };
  removeIceCream = () => {
    if (this.state.count > 0) {
      this.setState({ count: this.state.count - 1 });
    }
  };
  render() {
    return (
      <div>
        <h3>Ice Cream Cart 🍦</h3>
        <p>Total ice creams: {this.state.count}</p>
        <button onClick={this.addIceCream}>Add</button>
        <button onClick={this.removeIceCream}>Remove</button>
      </div>
    );
  }
}
export default IceCreamCart;

Output:

Ice Cream Cart 🍦

Total ice creams: 4
Add   Remove

Functional Components

Components That Are Functional Functional components are straightforward JavaScript functions that return a React element (JSX) after receiving a single “props” object argument containing data. Historically, they were known as “stateless functional components” due to the fact that they were incapable of managing internal state.

Key aspects of Functional Components:

Simplicity: Since there is no class overhead and there are no worries about this keyword, they are simpler to write and comprehend.

Hooks: Originally reserved for class components, hooks enable functional components to “hook into” React features like state and lifecycle methods. They were first introduced in React 16.8. For example, useEffect manages side effects in a manner akin to lifecycle methods, while the useState Hook manages states.

Props as arguments: Props can be destructured for simpler access and are supplied straight to the function as arguments.

Code Example (Functional Component):

import React, { useState, useEffect } from 'react';
// Functional Component that accepts props
function Greeting({ name }) {
  // useState Hook to manage state
  const [message, setMessage] = useState('Welcome!');
  // useEffect Hook simulates componentDidMount
  useEffect(() => {
    console.log('Greeting component mounted');
    setMessage(`Hello, ${name}!`);
    
    // Cleanup (optional): similar to componentWillUnmount
    return () => {
      console.log('Greeting component unmounted');
    };
  }, [name]); // Only re-run if 'name' changes
  return (
    <div>
      <h1>{message}</h1>
    </div>
  );
}
export default Greeting;

Output:

Hello, undefined!

Setting Up a React Project with Create React App

Creating a React Project with Create React App Start utilising React components by creating a React project with Create React App. This utility facilitates React project setup by offering all JavaScript libraries, including code transpiling (using Babel for JSX), basic linting, testing, and build systems. It allows development server hot reloading to update your page while coding.

To start a new project, type npx create-react-app <project-name> into your terminal. Run npm start in the project directory.src/App.js to render the remaining components when the development server has been constructed. React code can be linked to a public/index.html div with id=”root”.index.js render using ReactDOM.

Conclusion

React’s robust and adaptable UI development strategy is built on top of its component-based design. Developers can create complicated user interfaces more quickly by decomposing interfaces into reusable, independent components, whether these components are class-based or functional. While current programming increasingly favours functional components supplemented with Hooks for managing state and side effects in a simpler, more legible way, class components offer a conventional, stateful structure perfect for managing lifecycle events.

React’s performance and maintainability are influenced by its fundamental design principles, which include declarative design, composability, efficiency via the Virtual DOM, and unidirectional data flow. React applications with best practices integrated are simple to start up and grow with tools like Create React App, which further streamlines the development process.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index