Flat Preloader Icon

React Components

In React, a component is a self-contained unit of code that encapsulates the structure (HTML), behavior (JavaScript), and styling (CSS) necessary to render a part of the user interface. Components can be thought of as the building blocks of a React application, each responsible for rendering a specific piece of the UI.

In ReactJS, we have mainly two types of components.

  1. Functional Components
  2. Class Components

1. Functional Components:

  • These are JavaScript functions that return JSX (JavaScript XML), which describes what the UI should look like.
  • They do not manage their own state; instead, they receive data through props (properties).
				
					function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

				
			

2. Class Components:

  • These are ES6 classes that extend React.Component and can manage their own state.
  • They have lifecycle methods that allow them to execute code at specific points in the component’s life cycle.
				
					class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

				
			

Key Concepts

  • JSX: A syntax extension that allows writing HTML-like code within JavaScript. JSX is then transpiled to JavaScript by tools like Babel.
				
					const element = <h1>Hello, world!</h1>;

				
			
  • Props: Short for properties, props are read-only data passed from a parent component to a child component.
				
					function Greeting(props) {
  return <h1>Hello, {props.name}</h1>;
}

				
			
  • State: A built-in object that holds data that may change over the component’s lifecycle. State is managed within the component itself.
				
					class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }

  render() {
    return <h2>It is {this.state.date.toLocaleTimeString()}.</h2>;
  }
}

				
			
Summary: A component in React is a reusable, independent piece of the UI that can be composed to build complex applications. They promote modularity and code reusability, making the development process more efficient and organized.