How To Pass Values Parent Component To Child Component And Child Component To parent Component

First of all, we have to create an application in React. Below, I have detailed how we can pass the values Parent component to Child component and Child component to the Parent component.

We have create a 2 component parent component and child component.

ParentComponent.js

import React, { useState } from 'react'
import ChildComponent from './ChildComponent'

export default function PerentComponrnt() {
    const [valueA, setValueA] = useState(10)
    const [valueB, setValueB] = useState(10)
    const [total, setTotal] = useState(0)
    const addNumberfunc = () => {
        setTotal(Number(valueA) + Number(valueB))
    }
    return (
        <>
            <div style={{ textAlign: 'center' }}>
                <ChildComponent setValueA={setValueA} setValueB={setValueB} />
                <button onClick={() => addNumberfunc()}>Add Number</button>
                <h2>{total}</h2>
            </div>
        </>
    )
}

ChildComponent.js

import React from 'react'

export default function ChildComponent({ setValueA, setValueB }) {
    return (
        <>
            <h3>Number 1</h3>
            <input type="number" placeholder="Enter Value A" onChange={(e) => setValueA(e.target.value)} /><br />
            <h3>Number 2</h3>
            <input type="number" placeholder="Enter Value B" onChange={(e) => setValueB(e.target.value)} /><br /><br /> 
        </>
    )
}

Run the project. You will get the below output.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories