Home > database >  How do I get the Age data from child to parent component
How do I get the Age data from child to parent component

Time:06-26

Parent.js

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

const Parent = () => {
    const[data,setData] = useState('')
    const[name,setName] = useState('')
    const[toggled,setToggled] = useState(false)
    const[age,setAge] = useState('')

    const ageToChild = (ageData) =>{
        setAge(ageData)
    }
    const childToParent = (childData) =>{
        setData(childData)
    }

    const handleSubmit = (e) =>{
        e.preventDefault()
        alert(`Age is ${age} , Form Submitted`)
        console.log(`Name is ${name} and Age is ${age}`)
    }
  return (
    <>
        {data}
        <div>
            {/* <Child childToParent={childToParent}></Child> */}
            <form onSubmit={handleSubmit}>
                <label>Name : </label>
                <input type="text" value={name} onChange={(e)=>setName(e.target.value)}></input>
                <button type='button' onClick={()=>setToggled(!toggled)}>Age ?</button>
                {toggled && <Child childToParent={childToParent} ageToChild={ageToChild}></Child>}
                <button type='button'>Submit</button>
            </form>
        </div>
    </>
  )
}

export default Parent

Child.js

import React from 'react'

const Child = ({childToParent,ageToChild}) => {
    const data = "This is some data from the child component to parent"
    // const age = ageToChild
  return (
    <>
        <button onClick={()=>childToParent(data)}>Click Child</button>
        <label>Age : </label>
        <input type='text' onChange={()=>ageToChild()}></input>
    </>
  )
}

export default Child

I am getting output as Name is inputtedname and Age is Undefined , How do I get the user inputted age value logged in the console? I am trying to pass data from child to parent using functional components

CodePudding user response:

If you want to pass age value to alert() from Child.js component, you should add e.target.value to onChange:

<input type='text' onChange={(e)=>ageToChild(e.target.value)}></input>

CodePudding user response:

Make sure to pass the ageToChild function from the parent component to the child:

<Child childToParent={childToParent} ageToChild={ageToChild} />

Then from the Child component you can simply do:

<input type='text' onChange={(e)=> ageToChild(e.target.value)} />

CodePudding user response:

use this code:

<input type='text' onChange={(e)=>ageToChild(e.target.value)}></input>

CodePudding user response:

You have forgotten to pass the value in the function

  • Related