• Articles
  • Tutorials
  • Interview Questions

How to Use Props in React.js

We will also discuss some best practices for using props in React. So if you’re interested in learning more about props in React, read on!

The below-mentioned topics will be discussed in this blog:

Start Learning React from scratch watch our React JS Full Course:

Video Thumbnail

What are Props in React?

Props play a fundamental role in React as they facilitate the transfer of data from a parent component to its child components. They offer a means of customizing and configuring components, resulting in the dynamic rendering of data and behavior within a React application.

In React, components serve as the foundational building blocks of the user interface. They encapsulate specific functionalities, and they can be reused across the application. With the introduction of props, components can receive the necessary data required to accurately render and exhibit the desired behavior.

When a component is invoked or rendered, props serve as inputs or arguments that are passed to it. These props can contain diverse types of data, ranging from strings, numbers, booleans, objects, and arrays to even functions. By leveraging the power of props, developers gain control over the appearance, behavior, and content of components, making these props flexible and adaptable to various use cases.

Here is the basic example of React Props

import React from 'react';
// Parent component
function ParentComponent() {
  return (
    <div>
      <h1>Welcome to Props Example</h1>
      <ChildComponent name="John" age={25} />
    </div>
  );
}
// Child component
function ChildComponent(props) {
  return (
    <div>
      <h2>Child Component</h2>
      <p>Name: {props.name}</p>
      <p>Age: {props.age}</p>
    </div>
  );
}

Become an expert in React by learning from experts through our React JS Course.

export default ParentComponent;

In this example, we have a parent component called ParentComponent that includes a child component called ChildComponent. The parent component provides two props: name and age, which are passed to the child component.

Within the child component, we can access these props by using the props parameter in the function declaration. We can then utilize these react props to render dynamic content. In this particular case, we are displaying the name and age values received from the parent component.

When the parent component is rendered, it will exhibit the heading “Welcome to Props Example” and incorporate the child component with the name “John” and age “25”.

Props play a crucial role in facilitating the transfer of data from a parent component to its child component, empowering the creation of reusable and adaptable components within React.

Go through these Android Interview Questions to excel in your interview.

State and Props in ReactJS

ReactJS comes equipped with States as predefined objects.

State objects allow us to manage data within components by creating, manipulating or organizing it within their scope. Data may be passed along using props but can’t directly go from the state. Instead, all our information stays within each component through which its data management takes place.

ReactJS allows us to combine both states and props into an application in two steps, which are:
At first, our parent component needs to set the state. Once set, this state can then be passed as props into our child component.

Need for Props in React

Let’s delve into the primary reasons why props are indispensable in React:

  • Data Sharing: Props serve as a vital mechanism for data sharing between components within a React application. By passing props in react from parent components to their child components, data can seamlessly traverse the component tree. This facilitates effective communication and coordination among different parts of the application. This capability empowers developers to construct dynamic and interconnected user interfaces.
  • Component Reusability: Props are essential for encouraging component reuse. It is possible to alter a component’s behavior and appearance by passing different sets of props to it without changing the component itself. This enables the development of adaptable and modular components that can be employed in numerous application sectors. Code duplication is reduced, development efficiency is increased, and maintenance is made simpler as a result.
  • Configuration and Customization: Props offer an invaluable avenue for configuring and customizing components. By passing react specific props to a component, developers gain fine-grained control over its behavior, appearance, and content. This flexibility empowers components to adapt to diverse contexts and use cases, rendering them highly adaptable and well-suited for a wide range of application requirements.
  • Unidirectional Data Flow: React adheres to a unidirectional data flow architecture, wherein data flows exclusively from parent components to their child components via props. This unidirectional flow ensures predictable and maintainable application state management. By constraining direct modifications to props, React promotes superior data encapsulation and facilitates the traceability of data changes, ultimately contributing to more robust and comprehensible codebases.

Interested to know the implementation of callback function in javascript, then do checkout our blog on what is callback function in javascript!

Get 100% Hike!

Master Most in Demand Skills Now !

How to Use Props in React?

To use props in React, you can follow these steps:

  • In the parent component, define the child component and pass the desired data as props.
  • Use the props parameter in the function declaration or class component to access the props in the child component.
  • Utilize the props within the child component to render dynamic content or perform any necessary operations.

In this section, we will explore two approaches to utilizing props: one that doesn’t involve destructuring and another that employs destructuring.

Using Props without Destructuring

When we talk about using props without destructuring in React, it means accessing and utilizing props within a component without extracting them into individual variables. Instead, we directly access the props object by using the props parameter in the component’s function declaration.

In the parent component, define the child component and pass the props as attributes:

// Parent component
function ParentComponent() {
  return (
    <ChildComponent name="John" age={25} />
  );
}

In the child component, access the props by referencing the props object:

// Child component
function ChildComponent(props) {
  return (
    <div>
      <p>Name: {props.name}</p>
      <p>Age: {props.age}</p>
    </div>
  )
}

The child component receives the props as an argument (props) in the function declaration. The individual props can be accessed using dot notation (props.name, props.age) inside the component.

Here’s the complete code:

// Parent component
function ParentComponent() {
  return (
    <ChildComponent name="John" age={25} />
  );
}
// Child component
function ChildComponent(props) {
  return (
    <div>
      <p>Name: {props.name}</p>
      <p>Age: {props.age}</p>
    </div>
  );
}

In this example, the parent component renders the child component and passes two props: name with the value “John” and age with the value 25. The child component then displays these props by accessing them through the props object.

Kick start your learning journey of React.Js visit ReactJS Tutorial.

Using Props with Destructuring

Using props with destructuring in React involves extracting particular properties from the props object and assigning them to separate variables within a component. This approach enhances code readability by allowing direct access to the extracted props, instead of accessing them through the props object. By employing destructuring, you can conveniently access and utilize the necessary react props within the component, improving code clarity and maintainability.

Here’s an example demonstrating how to use props with destructuring in React:

// Parent component
function ParentComponent() {
  return (
    <ChildComponent name="John" age={25} />
  );
}
// Child component
function ChildComponent({ name, age }) {
  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  );
}

In this example, the parent component (ParentComponent) renders the child component (ChildComponent) and passes two props: name with the value “John” and age with the value 25.

Inside the child component, instead of accessing props through the props object, we use destructuring in the function parameter declaration to extract the specific props we want to use (name and age). This allows us to directly use the extracted props as variables within the component without referring to props.

By utilizing destructuring, the child component can access and utilize the name and age props directly, resulting in cleaner and more concise code.

Default Props in ReactJS

Default props in ReactJS allow you to set default values for props in a component. If a prop is not explicitly provided when the component is used, the default value will be used instead. This is useful for ensuring that components have a fallback value when certain props are not passed.

Here’s an example that demonstrates how to define default props in React:

// Child component
function ChildComponent(props) {
  return (
    <div>
      <p>Name: {props.name}</p>
      <p>Age: {props.age}</p>
    </div>
  );
}
// Setting default props
ChildComponent.defaultProps = {
  name: "John Doe",
  age: 30
};
// Parent component
function ParentComponent() {
  return (
    <ChildComponent />
  );
}

In this example, the ChildComponent is defined with two props: name and age. By setting ChildComponent.defaultProps, we assign default values to the props. If the parent component (ParentComponent) uses ChildComponent without passing specific values for name and age, the default values will be used. In the given code, when the ChildComponent is rendered within the ParentComponent without explicitly providing name and age props, the default values of “John Doe” and 30 will be displayed.

Default props ensure that components have fallback values, reducing the likelihood of errors when certain props are not provided by the parent component.

Get ready for your next React interview by going through the most asked React Interview Questions.

Setting Default Values for Props

Setting default values for props in React allows you to define fallback values that will be used if a prop is not explicitly provided. This ensures that the component behaves as expected even when certain props are missing. To set default values for props, you can use the defaultProps property of the component. Here’s an example:

// Child component
function ChildComponent(props) {
  return (
    <div>
      <p>Name: {props.name}</p>
      <p>Age: {props.age}</p>
    </div>
  );
}
// Setting default props
ChildComponent.defaultProps = {
  name: "John Doe",
  age: 30
};
// Parent component
function ParentComponent() {
  return (
    <ChildComponent />
  );
}

In this example, the ChildComponent is defined with name and age props. The ChildComponent.defaultProps property is used to assign default values to the props. If the parent component (ParentComponent) renders ChildComponent without explicitly passing name and age props, the default values (“John Doe” and 30) will be used instead.

Setting default react props ensures that the component always has fallback values, preventing errors when certain props are not provided.

Advantages of Props in React

Advantages of Props in React
  • Component Composition: Props allow you to compose and nest components together, passing data from parent components to child components. This enables you to create complex UI structures by combining smaller, reusable components.
  • Data Flow: Props ensure a unidirectional data flow in React, which means that data is passed from parent components down to child components. This promotes a predictable and easy-to-understand flow of data throughout the application.
  • Customization and Configuration: Props allow you to customize and configure child components according to the specific needs of the parent component. By passing different values or functions as props, you can tailor the behavior and appearance of components without modifying their internal implementation.
  • Code Reusability: Props enable component reusability, as you can reuse the same component with different props across your application. This saves development time and effort, as you can leverage existing components to build new features without duplicating code.

Use Cases of Props in React

Props in React have various use cases that make them an essential part of component development. Here are some common use cases where props are utilized in React:

Use cases of Props in React
  • Data Passing: Props are used to pass various types of data from a parent component to its child components. This can include text, numbers, arrays, objects, or functions. For example, you can pass user details to a user profile component or provide a list of items to a component responsible for rendering them.
  • Component Customization: Props enable you to customize and configure components based on different requirements. By passing props in react, you can modify the appearance, behavior, or functionality of a component. This could involve customizing styles, toggling features, or specifying different options for component rendering.
  • Conditional Rendering: Props allow for conditional rendering of components or specific parts of components. By passing a Boolean prop that controls visibility or conditionally-rendered content, you can dynamically determine what gets displayed based on certain states or data conditions.
  • Event Handling: Props can be used to pass event handlers from a parent component to its child components. This allows child components to trigger actions in the parent component. For instance, you can pass a function prop that handles a button click event in a child component. When the button is clicked, it invokes the function provided through props.

By leveraging props in these use cases, React components become more flexible, reusable, and adaptable to different scenarios.

React Props Best Practices

By following these best practices, React components will become easier to maintain, more energy-efficient, and less likely to cause errors when working with props.

  • Keep Props Simple and Readable: For easier code maintenance and readability, name props with clear and descriptive descriptions that make sense in terms of their function and use abbreviations or long names that won’t cause confusion for other developers.
  • Default Prop Values: Always specify default prop values whenever possible to ensure that components work as expected even if some props do not pass as specified or pass with unknown values. Doing this ensures your components stay functioning efficiently when some or all props do not pass as required or come from undefined sources.
  • Immutability of Props: Treat props as immutable; try not to alter their values directly within a component, instead use local variables for this purpose if modifications need be.
  • Destructuring Props: Destructuring is used to extract individual props from an object which has multiple props attached, which makes your code cleaner and simpler for understanding when working with multiple props at once.
  • Be Wary of Giving Unnecessary Props: Be mindful about which props and data you pass to components. Avoid giving large or redundant datasets if their use will not benefit the component in any way; this helps ensure its focus and efficiency is not disrupted.

Conclusion

As the market demands more sophisticated and interactive web applications, an understanding of the effective utilization of props in React will continue to be a valuable skill for developers. Mastering the use of props enables developers to create modular and reusable components, leading to more efficient development processes and maintainable codebases.

Course Schedule

Name Date Details
Web Development Courses 12 Oct 2024(Sat-Sun) Weekend Batch
View Details
Web Development Courses 19 Oct 2024(Sat-Sun) Weekend Batch
View Details
Web Development Courses 26 Oct 2024(Sat-Sun) Weekend Batch
View Details

About the Author

Techical Research Analyst - Front End Development

As a Technical Research Analyst, Kislaya specializes in Front End Development. He is a Full Stack Developer, known for crafting scalable architectures and user-centric interfaces. He has a massive international client base and is an expert in cloud computing, Linux, and Java Script, personifying a commitment to quality and information sharing.