DEV Community

Parthipan M
Parthipan M

Posted on

Props in React..

In React, props (short for "properties") are used to pass information from one component to another. The main purpose of props is to allow a parent component to send data to its child components.

  • Props cannot be modified by the receiving component.

  • They are strictly for reading data and should not be altered.

  • Props can be updated when the parent component’s state changes.

import React from 'react';

function Greet(props) {
    return <h1>Hello, {props.name}!</h1>;
}

function App() {
    return <Greet name="React Mani" />;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, React Mani!

  • Greet Component: Accepts props and renders the value of props.name inside an <h1> tag.

  • App Component: Renders the Greet component and passes "React Mani" to the name prop.

Syntax

<ComponentName propName="value"/>

Working of Props in React

Props in React work by allowing data to flow from a parent component to a child component, making components dynamic and reusable.

Steps to use Props:

  • Define an attribute and its value (data).

  • Pass it to the child component by using props.

  • Render the props data.

Passing Multiple Props

In React, a parent component can pass multiple props to a child component, where each prop may hold a different type of data such as text, numbers, arrays, or functions.

App.js

import React from 'react';
import Parent from './Parent';

function App() {
    const appStyle = {
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        margin: 0,
        fontFamily: 'Arial, sans-serif',
    };

    return (
        <div style={appStyle}>
            <Parent />
        </div>
    );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Parent.js

import React from 'react';
import Child from './Child';  

function Parent() {
    const parentStyle = {
        textAlign: 'center',  
    };

    return (
        <div style={parentStyle}>
            <h1>Welcome to the Parent Component!</h1>
            <Child name="React Mani" age={21} city="India" />
        </div>
    );
}

export default Parent;
Enter fullscreen mode Exit fullscreen mode

Child.js

import React from 'react';

function Child(props) {
    const childStyle = {
        marginTop: '20px',
        fontSize: '18px',
        color: '#333',
    };

    return (
        <div style={childStyle}>
            <h2>Hello, {props.name}!</h2>
            <p>You are {props.age} years old.</p>
            <p>You live in {props.city}.</p>
        </div>
    );
}

export default Child;
Enter fullscreen mode Exit fullscreen mode

Output

Welcome to the Parent Component!

Hello, React Mani!

You are 21 Years old.

You live in India.

Top comments (0)