0
0
Reactframework~5 mins

Passing props to components in React

Choose your learning style9 modes available
Introduction

Props let you send information from one component to another in React. This helps components share data and work together.

You want to show a user's name inside a greeting component.
You need to customize a button's label and color from its parent component.
You want to reuse a card component but show different content each time.
You want to pass a function to handle a button click inside a child component.
Syntax
React
function ChildComponent(props) {
  return <div>{props.message}</div>;
}

function ParentComponent() {
  return <ChildComponent message="Hello!" />;
}

Props are passed like HTML attributes when using a component.

Inside the child, props is an object holding all passed values.

Examples
This passes the name 'Alice' to the Welcome component, which shows it.
React
function Welcome(props) {
  return <h1>Welcome, {props.name}!</h1>;
}

function App() {
  return <Welcome name="Alice" />;
}
Props customize the button's label and background color.
React
function Button(props) {
  return <button style={{ backgroundColor: props.color }}>{props.label}</button>;
}

function App() {
  return <Button label="Click me" color="blue" />;
}
A function is passed as a prop to handle the button click.
React
function AlertButton({ onAlert }) {
  return <button onClick={onAlert}>Alert</button>;
}

function App() {
  const showAlert = () => alert('Button clicked!');
  return <AlertButton onAlert={showAlert} />;
}
Sample Program

This app shows two greetings with different names by passing props to the Greeting component.

React
import React from 'react';

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

export default function App() {
  return (
    <main>
      <Greeting user="Sam" />
      <Greeting user="Lee" />
    </main>
  );
}
OutputSuccess
Important Notes

Props are read-only inside the child component; do not try to change them.

Use destructuring like function Greeting({ user }) for cleaner code.

Always give props meaningful names to keep code clear.

Summary

Props send data from parent to child components.

They look like HTML attributes when used.

Inside the child, props are accessed as an object.