In React, props (short for properties) are a way to pass data from a parent component to a child component.
Props are arguments that we pass to a React component from one component to another component.
Props are `immutable`, meaning they cannot be modified by the child component. This ensures data integrity and predictable component behaviour. Eventually, with the help of the callback function we receive from a parent component we can trigger callback action from the client component and the parent component can update props and send new props to the child component.
Data flow in React is `uni-directional`. Data flow from parent to child components, promoting a clear and predictable data flow architecture.
They allow us to customize and configure a component's behaviour or appearance.
We can pass any Javascript value as a prop, including primitive values, functions, or even JSX elements.
Props are a crucial part of the React component architecture, enabling the creation of reusable and configurable components.
// ParentComponent.js import React from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { // data to be passed as props const payload = 'Hello from Parent Component'; return ( <div> {/* Pass data as a prop to Child Component */} <ChildComponent message={payload} /> </div> ); }; export default ParentComponent;
ParentComponent passes a property named `message` to ChildComponent.
// ChildComponent.js import React from 'react'; const ChildComponent = (props) => { // Access the data passed as a prop const { message } = props; return ( <div> {/* Display the data received from props */} <p>{message}</p> </div> ); }; export default ChildComponent;
ChildComponent receives the props as an object named `props` and extracts the value of the `message` from props.
The value of the `message` is then displayed in the rendered output.
// ParentComponent.js import React from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { // data to be passed as props const listPayload = ['John', "Alice", "wick"]; return ( <div> {/* Pass data as a prop to Child Component */} <ChildComponent list={listPayload} /> </div> ); }; export default ParentComponent;
ParentComponent passes a property named `list` to ChildComponent.
// ChildComponent.js import React from 'react'; const ChildComponent = (props) => { // Access the data passed as a prop const { list } = props; return ( <div> <p>Below List will get rendered</p> {/* Display the data received from props */} {list.map((item) => { return ( <p>Hi, <h3>{item}</h3></p> ) } </div> ); }; export default ChildComponent;
ChildComponent receives the props as an object named `props` and extracts the value of the `list` from props.
The value of the `list` is then iterated with the help of a `map` method and displayed in the rendered output.