Skip to main content

Props

In React, "props" is short for "properties." Props are a way to pass data from one component to another, essentially making them a mechanism for component-to-component communication. They are similar to function arguments: just as you pass arguments to a function, you pass props to a React component.

Basic Usage

Here's a simple example to demonstrate how props work:

// A functional component that takes a prop 'name'
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}

// Using the component and passing a 'name' prop to it
const element = <Greeting name="John" />;

In this example, the Greeting component has a props parameter. When the component is used, you can pass a name prop to it, which will be accessible within the component as props.name.

Immutable Nature

It's important to note that props are "read-only," which means that a component should never modify the props passed to it. Doing so is considered bad practice and can lead to unpredictable behavior.

// Don't do this
function BadGreeting(props) {
props.name = "Default Name"; // Modifying props is bad practice
return <h1>Hello, {props.name}!</h1>;
}

Passing Different Types of Data

Props can be of any data type, including:

  • Strings
  • Numbers
  • Booleans
  • Arrays
  • Objects
  • Functions
function Profile(props) {
return (
<div>
<h1>{props.name}</h1>
<p>Age: {props.age}</p>
<p>Skills: {props.skills.join(", ")}</p>
</div>
);
}

const element = <Profile name="John" age={30} skills={["JavaScript", "React"]} />;

Passing Booleans

Booleans are often used for conditional rendering or toggling features on and off.

// Parent Component
function App() {
return <ChildComponent isActive={true} />;
}

function ChildComponent() {
return <ChildComponent isActive />; // Here the isActive is property of ChildComponent of type boolean, and it will take true when mentioned but not passed any value
// return <ChildComponent isActive={false} />; // set props.isActie to false
// return <ChildComponent />; // set props.isActie to default value if set or undefined which is a javascript falsy value.
}

// Child Component
function ChildComponent({ isActive }) {
return <div>{isActive ? "Active" : "Inactive"}</div>;
}


Passing Arrays

Arrays are useful for rendering lists of items.

// Parent Component
function App() {
const fruits = ["Apple", "Banana", "Cherry"];
return <ChildComponent items={fruits} />;
}

// Child Component
function ChildComponent({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}

Passing Objects

Objects can be used to pass multiple related values as a single prop.

// Parent Component
function App() {
const user = { name: "John", age: 30 };
return <ChildComponent userInfo={user} />;
}

// Child Component
function ChildComponent({ userInfo }) {
return (
<div>
<p>Name: {userInfo.name}</p>
<p>Age: {userInfo.age}</p>
</div>
);
}

Passing Functions

Functions are often passed as props to handle events or modify parent component state.

// Parent Component
function App() {
const [count, setCount] = useState(0);

const incrementCount = () => {
setCount(count + 1);
};

return <ChildComponent onIncrement={incrementCount} />;
}

// Child Component
function ChildComponent({ onIncrement }) {
return <button onClick={onIncrement}>Increment</button>;
}

Important Notes:

  • Immutability: When passing arrays or objects, remember that React assumes that props are immutable. If you need to modify an array or object, it's good practice to create a new one.

  • Function Binding: When passing functions, especially to class components, you may need to bind the function to the current instance using .bind(this) or arrow functions.

  • Type Checking: For better maintainability and debugging, you can use PropTypes to specify the expected type of each prop.

Default Props

You can set default values for props using the defaultProps attribute on a component.

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

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

Destructuring Props

You can use JavaScript's destructuring assignment to unpack values from the props object, making your code cleaner.

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

Children Prop

The children prop is special and allows you to pass components as data to other components, rather than through attributes.

function Card(props) {
return <div className="card">{props.children}</div>;
}

const element = (
<Card>
<h1>Hello!</h1>
<p>Welcome to React.</p>
</Card>
);

In this example, the Card component uses props.children to render whatever you include between the opening and closing <Card> tags.

Props are a fundamental concept in React, enabling you to create reusable and interactive UI components.

PropTypes

In React, PropTypes are a way to enforce type-checking on the props passed to a component. They help catch bugs early by ensuring that the data you expect to be passed to a component is actually being received. PropTypes are especially useful in larger codebases or when working with multiple developers, as they serve as a form of documentation on how a component should be used.

To use PropTypes, you first need to import the prop-types package. If it's not already installed, you can install it via npm:

npm install prop-types

Then, you can specify the expected types for each prop your component receives:

import PropTypes from 'prop-types';

const MyComponent = ({ name, age, isActive }) => {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
<p>Active: {isActive ? 'Yes' : 'No'}</p>
</div>
);
};

MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
isActive: PropTypes.bool
};

In this example, the MyComponent component expects three props:

  • name: A required string
  • age: A number (optional)
  • isActive: A boolean (optional)

Supported Prop Types

Here are some commonly used PropTypes:

  • PropTypes.string: Validates that the prop is a string.
  • PropTypes.number: Validates that the prop is a number.
  • PropTypes.bool: Validates that the prop is a boolean.
  • PropTypes.array: Validates that the prop is an array.
  • PropTypes.object: Validates that the prop is an object.
  • PropTypes.func: Validates that the prop is a function.
  • PropTypes.node: Validates that the prop can be rendered (e.g., a number, string, element, or an array of these).
  • PropTypes.element: Validates that the prop is a React element.
  • PropTypes.oneOf([...]): Validates that the prop is one of the specified values.
  • PropTypes.oneOfType([...]): Validates that the prop is one of the specified types.
  • PropTypes.arrayOf(PropTypes.number): Validates that the prop is an array of numbers.
  • PropTypes.objectOf(PropTypes.string): Validates that the prop is an object with values of a certain type.

Default Props

You can also specify default values for optional props using the defaultProps property:

MyComponent.defaultProps = {
age: 30,
isActive: false
};

Custom Validators

You can even write custom validation functions for more complex validation:

MyComponent.propTypes = {
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
`Invalid prop ${propName} supplied to ${componentName}. Validation failed.`
);
}
}
};