ReactJS Component

react

In React, a component is a self-contained unit of code that represents a part of the UI (user interface) of an application. Components are reusable and can be nested inside other components, allowing you to build complex UIs by composing simple components.

There are two types of components in React: functional components and class components.

Functional components are simple JavaScript functions that take in props (short for properties) and return a JSX element that describes the UI of the component. They do not have state (data that changes over time) or lifecycle methods ( methods that are called at specific points in the component’s lifecycle).

Here is an example of a functional component in React:

import React from 'react';

function Button(props) {
    return (
        <button style={{color: props.color}} onClick={props.onClick}>
            {props.children}
        </button>
    );
}

export default Button;

This defines a Button component that takes in three props: color, onClick, and children. The color prop is used to set the color of the button text, the onClick prop is used to specify an event handler function that will be called when the button is clicked, and the children prop is used to specify the content of the button (the text or elements inside the button).

Class components are JavaScript classes that extend the React.Component class and define a render method that returns a JSX element. Class components can have state and lifecycle methods, which allow them to handle more complex UI behavior.

Here is an example of a class component in React:

import React from 'react';

class Counter extends React.Component {
    state = {count: 0};

    handleClick = () => {
        this.setState({count: this.state.count + 1});
    };

    render() {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.handleClick}>Increment</button>
            </div>
        );
    }
}

export default Counter;

This defines a Counter component that displays a count and has a button to increment the count. The state property is used to store the count, and the handleClick method is used to update the count when the button is clicked. The render method returns a JSX element that displays the count and the button.