Props
React Props (Properties)
React allows developers to create dynamic and reusable components using props (properties). Props are similar to HTML attributes. Each component can receive attributes, and their values can be accessed inside the component using props.
For example, a Hello component with a name attribute:
Inside the component, the value can be accessed as:
this.props.name
So, the value of name will be "React".
Types of Values Supported by Props
React props can accept values of different data types, such as:
String
Number
Date / DateTime
Array
List
Object
Using Props in React
When a component needs immutable data (data that does not change inside the component), props are used. Props are usually passed from ReactDOM.render() or from a parent component.
Example: Using Props
App.jsx
import React from 'react'; class App extends React.Component { render() { return (
{this.props.headerProp}
{this.props.contentProp}
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(
Output
Header from props... Content from props...
Default Props
React allows you to define default values for props. These values are used when no props are passed to the component.
Example: Default Props
App.jsx
import React from 'react'; class App extends React.Component { render() { return (
{this.props.headerProp}
{this.props.contentProp}
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(
Output
The output remains the same as before, even though no props were explicitly passed.
State vs Props
Props are used to pass data from parent to child components
State is used to store and manage data within a component
Props are read-only
State can be updated
Example: Combining State and Props
In this example, the parent component stores data in its state and passes it to child components using props.
App.jsx
import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { header: "Header from props...", content: "Content from props..." }; } render() { return (
{this.props.headerProp}
{this.props.contentProp}
main.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(
Explanation
The App component stores data in its state
State values are passed to Header and Content components as props
When the state changes, React automatically re-renders all child components
This makes data flow predictable and easy to manage