Dung (Donny) Nguyen

Senior Software Engineer

Props

Props, short for “properties,” are a key concept in React.js used to pass data from one component to another, typically from a parent component to a child component. Props are immutable, meaning they are read-only and cannot be modified by the receiving component. Here’s a deeper look at how props work and why they are essential:

Key Characteristics of Props

Example of Using Props

Functional Component

Here’s an example of passing props to a functional component:

import React from 'react';

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

function App() {
  return <Greeting name="Alice" />;
}

export default App;

In this example:

Class Component

Here’s an example using a class component:

import React, { Component } from 'react';

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

class App extends Component {
  render() {
    return <Greeting name="Alice" />;
  }
}

export default App;

In this example:

Props with Default Values

We can also set default values for props using defaultProps:

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

Greeting.defaultProps = {
  name: 'Guest',
};

function App() {
  return <Greeting />;
}

export default App;

In this example, if the name prop is not provided, the Greeting component will use 'Guest' as the default value.

Why Props Are Important

Props are an essential part of React.js, enabling us to create dynamic, flexible, and reusable components.