Class Components
In this approach props values will be accessed inside a class component using this keyword inside the JSX code written in render() method or any other class method.
For example – this.props.propName – where propName is the actual property whose values are being passed from App component to class component. and this.props is a way to access
Syntax:
class ComponentName extends React.Component {
render() {
return <div>{this.props.propName}</div>
}
}
Example: Below is an example of accessing props using class components.
import React from 'react';
class ClassComponentName extends React.Component {
render() {
return <div>{this.props.propName}</div>;
}
}
export default ClassComponentName;
Output:
Different ways to access props inside a Component in React
The props keyword is the shorthand for properties. It is one of the most important features of React which helps in effective communication between various React components. It is a read-only attribute for passing data from the parent component to the child component. There are various ways to access props inside a component.
We will discuss the ways to access props inside a component.
Table of Content
- Functional Components:
- Class Components:
- Destructuring
- Using Context API:
- Using useContext() hook: