Props in React: Passing Data Between Components
In React, components are the building blocks of user interfaces. But how do components talk to each other or share data? The answer lies in props. Short for “properties,” props are a core concept in React used to pass data from one component to another, usually from parent to child.
What Are Props?
Props are read-only objects that allow you to send data into a component. They work similarly to arguments passed to a function. A parent component can pass any type of data to a child component using props — including strings, numbers, arrays, objects, functions, or even other components.
Here’s a basic example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Greeting name="Alice" />;
}
In this case, the App component passes the name prop to the Greeting component, which renders: “Hello, Alice!”
Props Are Read-Only
One of the fundamental rules in React is that props cannot be changed by the receiving component. They are immutable. If you need to change data inside a component, use state instead.
Attempting to modify props will result in warnings and bad application design.
Using Destructuring
To make the code cleaner and more readable, you can destructure props:
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
This way, you can access props directly without writing props.name.
Passing Functions via Props
You can also pass functions as props, which allows child components to communicate back to the parent. This is essential for handling user events or updating shared state.
function Button({ onClick }) {
return <button onClick={onClick}>Click Me</button>;
}
function App() {
const handleClick = () => alert("Button clicked!");
return <Button onClick={handleClick} />;
}
Final Thoughts
Props in React enable flexible and dynamic component structures. They are essential for component reuse, data flow, and parent-child communication. Mastering props helps build scalable, modular UIs where components can easily be composed and managed. While props send data down the tree, advanced patterns like Context API or Redux help manage more complex state and communication across the app.
Learn MERN Stack Training Course
Building a Mini JavaScript Project: Calculator or Weather App
Introduction to React and Single Page Applications (SPAs)
Setting Up a React Project with Create React App or Vite
Functional Components vs Class Components
Visit Our Quality Thought Training Institute
Comments
Post a Comment