0
0
Reactframework~5 mins

Props as read-only data in React

Choose your learning style9 modes available
Introduction

Props let components get information from their parent. They are read-only so components don't change data they don't own.

Passing a user name from a parent to a child component to display it.
Sending a color value to style a button without changing it inside the button.
Sharing a list of items from a parent to a child for showing in a list.
Giving a child component a callback function to notify the parent about an event.
Syntax
React
function ChildComponent(props) {
  return <div>{props.message}</div>;
}

// Usage
<ChildComponent message="Hello!" />

Props are passed like HTML attributes when using a component.

Inside the component, props are read-only and should not be changed.

Examples
Pass a simple string prop to show a greeting.
React
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

<Greeting name="Alice" />
Pass multiple props to customize button text and color.
React
function Button(props) {
  return <button style={{ backgroundColor: props.color }}>{props.label}</button>;
}

<Button color="blue" label="Click me" />
Pass an array prop to render a list of items.
React
function List(props) {
  return <ul>{props.items.map(item => <li key={item}>{item}</li>)}</ul>;
}

<List items={["Apple", "Banana", "Cherry"]} />
Sample Program

This simple app shows how a child component receives a message prop and displays it without changing it.

React
import React from 'react';

function DisplayMessage(props) {
  // Trying to change props.message here would be wrong
  return <p>{props.message}</p>;
}

export default function App() {
  return (
    <div>
      <DisplayMessage message="Props are read-only!" />
    </div>
  );
}
OutputSuccess
Important Notes

Never try to modify props inside a component; it can cause bugs and unexpected behavior.

If you need to change data, use component state or context instead.

Props help keep components predictable and easy to understand.

Summary

Props pass data from parent to child components.

Props are read-only inside the receiving component.

Use state if you need to change data within a component.