PROPS in React
Hey there! 👋 I'm Pratyush, a results-driven Full Stack Developer with a deep love for turning innovative ideas into scalable and robust software solutions.
In React, "props" is short for "properties," and it refers to a system for passing data from a parent component to a child component. Props are a way to customize or configure a component by providing it with the information it needs to render correctly or behave in a certain way.
Props (Properties):
Definition: Props are a mechanism in React for passing data from one component (the parent) down to another component (the child).
Role: Props allow components to be dynamic and configurable. They enable the parent component to control and customize the behavior and appearance of child components.
Immutable: Props are immutable, meaning that their values cannot be changed by the component that receives them. A child component should not modify the values of its props.
Syntax: Props are specified in a manner similar to HTML attributes. When you use a component in JSX, you can pass props by adding attributes to the component tag. For example:
<ChildComponent propName={propValue} />
Accessing Props: In the child component, props are accessed through a JavaScript object named
props. For example:const ChildComponent = (props) => { // Accessing a prop named "propName" const propValue = props.propName; // ... };Passing Functions as Props: In addition to data, functions can also be passed as props. This allows communication and interaction between parent and child components.
Dynamic Rendering: Props are often used to dynamically render components based on varying data
In summary, props are a fundamental concept in React that facilitates the flow of data between components, enabling the building of flexible, reusable, and configurable UIs.
Lets have a look at simple example...
Lets create a simple component Hello.js
import React from "react";
const Hello = (props) => {
const textElement = props.text();
return (
<div>
<h1>Greetings from the Hello component!</h1>
{/* Render the JSX element received from the parent */}
{textElement}
</div>
);
};
export default Hello;
Now lets send props from the parent App.js to Hello.js
import React from "react";
import Hello from "./components/Hello";
const App = () => {
// Define a function that returns a JSX element
const text = () => {
return <p>Hello, this is a prop from parent APP.JS</p>;
};
// Return the Hello component and pass the text function as a prop
return (
<>
<Hello text={text} />
</>
);
};
export default App;
Now the final output is:
