fbpx

React Components and Props

In React, components are the building blocks of a user interface, and props are a way to pass data from a parent component to a child component. Let’s explore React components and props in more detail:

React Components:

A React component is a reusable, self-contained piece of UI that can be composed to build larger applications. Components can be either functional or class-based.

Functional Components:

Functional components are simpler and more concise, especially with the introduction of React Hooks.

import React from 'react';

function Greeting(props) {
  return <div>Hello, {props.name}!</div>;
}

export default Greeting;

Class Components:

Class components have additional features, such as lifecycle methods, and were the primary way of creating components before the introduction of hooks.

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <div>Hello, {this.props.name}!</div>;
  }
}

export default Greeting;

React Props:

Props (short for properties) are a way to pass data from a parent component to a child component. They are immutable, meaning that the child component cannot modify the props it receives.

Passing Props to Components:

You can pass props to a component by including them in the component tag. The child component can then access the props through its function parameters.

// ParentComponent.js
import React from 'react';
import Greeting from './Greeting';

function ParentComponent() {
  return <Greeting name="John" />;
}

export default ParentComponent;

Accessing Props in Components:

In functional components, props are accessed through the function parameters.

// Greeting.js (Functional Component)
import React from 'react';

function Greeting(props) {
  return <div>Hello, {props.name}!</div>;
}

export default Greeting;

In class components, props are accessed through the this.props object.

// Greeting.js (Class Component)
import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <div>Hello, {this.props.name}!</div>;
  }
}

export default Greeting;

Default Props:

You can provide default values for props using the defaultProps property. These values will be used if the parent component does not provide the corresponding prop.

// Greeting.js (Functional Component)
import React from 'react';

function Greeting(props) {
  return <div>Hello, {props.name}!</div>;
}

Greeting.defaultProps = {
  name: 'Guest',
};

export default Greeting;

Conclusion:

Understanding React components and props is fundamental to building React applications. Components allow you to create modular and reusable pieces of UI, and props enable you to pass data between these components. As you delve deeper into React development, you’ll encounter more advanced concepts, such as state, lifecycle methods, and context, which further enhance the capabilities of React components.