Passing and Accessing Props in React JS 🎯

beginner
12 min

Passing and Accessing Props in React JS 🎯

Welcome to our comprehensive guide on passing and accessing props in React JS! In this lesson, we'll explore how to effectively communicate data between components in a React application. Let's dive in!

Understanding Props 📝

Props, short for properties, are a way to pass data from a parent component to a child component in React. They are similar to function parameters, and they make your components more flexible and reusable.

Syntax for Defining Props 💡

In a functional component, props are defined as function parameters:

jsx
function ChildComponent(props) { // Access props using props.propertyName return <div>{props.message}</div>; }

In a class-based component, props are defined as class properties:

jsx
class ChildComponent extends React.Component { render() { // Access props using this.props.propertyName return <div>{this.props.message}</div>; } }

Passing Props to Child Components 💡

To pass props to a child component, simply include them as attributes in the JSX opening tag:

jsx
function App() { return <ChildComponent message="Hello from Parent!" />; }

Accessing Props in Child Components 💡

As mentioned earlier, you can access props in both functional and class-based components:

Functional Component

jsx
function ChildComponent(props) { return <div>{props.message}</div>; } function App() { return <ChildComponent message="Hello from Parent!" />; }

Class-Based Component

jsx
class ChildComponent extends React.Component { render() { return <div>{this.props.message}</div>; } } class App extends React.Component { render() { return <ChildComponent message="Hello from Parent!" />; } }

Passing Multiple Props 📝

You can pass multiple props by separating them with spaces:

jsx
function App() { return <ChildComponent message="Hello from Parent!" color="blue" />; } function ChildComponent(props) { return ( <div style={{ color: props.color }}> {props.message} </div> ); }

Accessing Props with Dot Notation 💡

You can also access props using dot notation:

jsx
function ChildComponent(props) { return <div style={{ color: props.color }}>{props.message}</div>; } function App() { return <ChildComponent message="Hello from Parent!" color="blue" />; }

Passing Complex Props 💡

Props can be objects or arrays as well:

jsx
function ChildComponent(props) { return <div>{props.data.message}</div>; } function App() { const data = { message: "Hello from Parent!" }; return <ChildComponent data={data} />; }

Quiz 🎯

Quick Quiz
Question 1 of 1

What are Props in React JS?

That's it for this lesson! We've covered the basics of passing and accessing props in React JS. In the next lesson, we'll dive deeper into more advanced prop concepts. Happy coding! 🚀🌟