What is React Props ?

In React, props (short for “properties”) are a mechanism to pass data from one component to another, specifically from a parent component to a child component. They help make components reusable and dynamic, as they allow for data to be passed and used flexibly within different instances of the same component.

1. Passing Props to Child Components

Props are passed to a child component by adding them as attributes in the JSX of the parent component. For example:

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


function ChildComponent(props) {
  return <p>{props.message}</p>;
}

In this example:

message=”Hello from parent!” is the prop being passed to ChildComponent.

props.message is used in ChildComponent to access the passed value and render it.

2. Accessing Props in the Child Component

Props can be accessed in the child component by using props. <propName>. Often, props are passed as a single object (props), but you can also destructure them for cleaner code:

function ChildComponent({ message }) {
  return <p>{message}</p>;
}

3. Prop Types

Props can be of any data type—strings, numbers, arrays, functions, objects, etc. For example:

function ChildComponent({ name, age, isStudent }) {
  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Student: {isStudent ? 'Yes' : 'No'}</p>
    </div>
  );
}


// Passing different prop types
<ChildComponent name="Alice" age={20} isStudent={true} />;

4. Prop Validation (Optional)

React allows you to define expected prop types using PropTypes. This is optional but can help with debugging by ensuring the correct types of props are passed. You can add propTypes to your component like this:

import PropTypes from 'prop-types';


function ChildComponent({ message }) {
  return <p>{message}</p>;
}


ChildComponent.propTypes = {
  message: PropTypes.string.isRequired,
};

Here:

PropTypes.string.isRequired specifies that message must be a string and is required for ChildComponent to function correctly.

5. Default Props

You can define default values for props by using defaultProps. This is useful when you want a fallback value if a prop isn’t provided.

ChildComponent.defaultProps = {
  message: 'Default message',
};

6. Props Are Read-Only

Props are immutable, meaning they cannot be changed once passed to a component. This rule enforces one-way data flow and helps keep React components predictable. To modify values, you would typically use state (managed internally within the component) or modify the value in the parent component and pass a new prop.

Leave a comment

Your email address will not be published. Required fields are marked *