ReactJS – Properties (props)
Props, short for properties, are used in React to pass data from one component to another, typically from a parent component to a child component. Props are read-only, meaning they cannot be modified by the component that receives them.
Example: Passing Props in a React Application
Let’s create a simple example where a parent component passes props to a child component.
Step 1: Create a React Application
First, make sure you have a React application set up. If you don’t have one, you can create it using Create React App:
npx create-react-app props-example
cd props-example
npm start
Step 2: Create Components
Let’s create a parent component called App
and a child component called Greeting
.
App Component (Parent)
// src/App.js
import React from 'react';
import Greeting from './Greeting';
function App() {
const name = "John";
return (
<div>
<Greeting name={name} />
</div>
);
}
export default App;
Greeting Component (Child)
// src/Greeting.js
import React from 'react';
function Greeting(props) {
return (
<h1>Hello, {props.name}!</h1>
);
}
export default Greeting;
Step 3: Run the Application
Now, when you run the application, it will display “Hello, John!” on the screen.
Explanation
- App Component (Parent):
- We define a variable
name
with the value"John"
. - We use the
Greeting
component and pass thename
variable as a prop with the syntax<Greeting name={name} />
.
- We define a variable
- Greeting Component (Child):
- The
Greeting
component receives the props as an argument in its function. We can access the props usingprops.name
. - The component renders an
h1
element with the text “Hello, John!”.
- The
Key Points
- Passing Props: In the parent component, you pass props to a child component by adding attributes to the child component. The attribute name becomes the prop name, and the attribute value becomes the prop value.
- Accessing Props: In the child component, you can access the props using the
props
object. In a functional component,props
is passed as an argument to the function. - Read-Only: Props are read-only. The child component should not modify the props it receives. If you need to update the data, it should be done in the parent component, which can then pass the updated data down as new props.
This is a basic example of how props work in React. As you build more complex applications, you’ll find that props are a powerful way to pass data and configuration between components.