Props in React step by step Guide

Step 1: What are Props?

  • Props (short for properties) are a way to pass data from a parent component to a child component in React.

  • They are used to make components more dynamic and reusable.

Step 2: Why Use Props?

  • Props allow you to customize the behavior and appearance of child components.

  • They help in maintaining a unidirectional data flow, where data flows from parent to child.

  • Props make it easy to reuse components with different data.

Step 3: Passing Props

  • In a parent component, you specify props when rendering a child component by adding attributes to it.

Example:

// Parent Component
function App() {
  return (
    <ChildComponent name="John" age={30} />
  );
}

Step 4: Receiving Props

  • In the child component, you can access the props passed to it as an object.

Example:

// Child Component
function ChildComponent(props) {
  return (
    <div>
      <p>Name: {props.name}</p>
      <p>Age: {props.age}</p>
    </div>
  );
}

Step 5: Rendering Child Components

  • When the parent component renders the child component, it can provide different values for the props.

Example:

function App() {
  return (
    <div>
      <ChildComponent name="Alice" age={25} />
      <ChildComponent name="Bob" age={28} />
    </div>
  );
}

Step 6: Using Props Dynamically

  • Props can be used dynamically within the child component to display data.

Example:

function ChildComponent(props) {
  return (
    <div>
      <p>Name: {props.name}</p>
      <p>Age: {props.age}</p>
    </div>
  );
}

That's a simplified step-by-step explanation of props in React. They enable you to customize and share data between components, enhancing the flexibility and reusability of your application.