Props in React.js with Examples
Props in React.js with Examples
Props
(short for "properties") in React are used to pass data from a parent
component to a child component. They are read-only and help make components
reusable.
1. Functional Component Example (Using Props)
In
functional components, props are received as function parameters.(Arrow
function)
Three.js
App.js
Function Component example Two
Explanation:
- The Student component receives props and displays name and course.
- The App component passes different
values for name and course to different Student components.
2. Class Component Example (Using Props)
In class
components, props are accessed via this.props.
import React, { Component } from "react";
Explanation:
- In the Student class component, this.props.name and this.props.course are used to access the
passed props.
- The App component passes different
props to different instances of the Student component.
Key Differences Between Functional and Class
Components for Props
|
Feature |
Functional Component |
Class Component |
|
Syntax |
Uses function
parameters |
Uses this.props |
|
Readability |
More
concise and easier to read |
More
verbose |
|
State
Management |
Uses useState (Hooks) |
Uses this.state |
|
Performance |
More
performant as there is no this
binding |
Less
performant due to this binding |
Conclusion
- Use functional components
with props when possible, as they are simpler and preferred in modern
React (with hooks).
- Use class components
only when working with legacy codebases.
Comments
Post a Comment