0
0
ReactHow-ToBeginner · 3 min read

How to Access Props in React Component: Simple Guide

In React, you access props in a functional component by adding a props parameter to the function and then using props.propertyName. You can also use JavaScript destructuring to directly extract specific props for cleaner code.
📐

Syntax

To access props in a React functional component, define a parameter named props in the function. Then use props.propertyName to get the value passed from the parent component. Alternatively, use destructuring to extract props directly in the function signature.

  • props: The object containing all passed properties.
  • props.propertyName: Access a specific prop by its name.
  • Destructuring: Extract props like { propertyName } for simpler code.
jsx
function MyComponent(props) {
  return <div>{props.title}</div>;
}

// Using destructuring
function MyComponent({ title }) {
  return <div>{title}</div>;
}
💻

Example

This example shows a parent component passing a name prop to a child component. The child accesses and displays the prop using destructuring.

jsx
import React from 'react';

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

export default function App() {
  return <Greeting name="Alice" />;
}
Output
Hello, Alice!
⚠️

Common Pitfalls

Common mistakes when accessing props include:

  • Forgetting to include props or destructure it in the function parameters.
  • Trying to access props without the props. prefix or destructuring.
  • Mutating props instead of treating them as read-only.

Always remember props are read-only and must be accessed correctly.

jsx
/* Wrong way: missing props parameter */
function Welcome() {
  return <h1>Hello, {name}!</h1>; // 'name' is undefined
}

/* Right way: include props or destructure */
function Welcome({ name }) {
  return <h1>Hello, {name}!</h1>;
}
📊

Quick Reference

ConceptUsage Example
Access all propsfunction Comp(props) { return
{props.title}
; }
Destructure propsfunction Comp({ title }) { return
{title}
; }
Pass props
Props are read-onlyDo not modify props inside component

Key Takeaways

Access props by adding a parameter named props or destructuring it in the component function.
Use props.propertyName or destructured variables to read prop values.
Props are read-only; never try to change them inside the component.
Always include props or destructure in the function signature to avoid undefined errors.
Passing props from parent to child components allows dynamic and reusable UI.