React Props

  • In React, "props" is a shorthand for "properties."
  • Props are a way to pass data from a parent component to a child component.

Passing Props to Functional Components

In functional components, props are passed as an argument.

import React from 'react';

const Greeting = (props) => {
  return <h1>Hello, {props.name}!</h1>;
};

Passing Props to Class Components

In class components, props are accessed via `this.props.`

import React, { Component } from 'react';

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

Default Props

You can set default values for props using `defaultProps.`

import React from 'react';

const GreetingWithDefault = (props) => {
  return <h1>Hello, {props.name}!</h1>;
};

GreetingWithDefault.defaultProps = {
  name: 'Guest'
};

Children Props

Props can also be used to pass JSX elements as children.

import React from 'react';

const Card = (props) => {
  return (
    <div className="card">
      {props.children}
    </div>
  );
};

Props in Action

Example of using props in a parent and child component.

// Parent Component
import React from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  return <ChildComponent message="Hello from Parent" />;
};

// Child Component
import React from 'react';

const ChildComponent = (props) => {
  return <p>{props.message}</p>;
};

 

Summary

Understanding how to use and pass props is crucial for creating dynamic and reusable components in React. Whether functional or class components, props provide a means of communication between different parts of your application.