-1

I have two components one child and another is parent component. I am conditionally rendring my child component. Function of this code is just when you click on button a timer will display and when you click stop timer will stop. Here "Timer" is child componenet and I have used state property in "timer" componenet and I want to display the value of Timer when a just before clicking on "stop timer button". So how do I pass the "timer" state variable value from child to parent component.

 const[time,setTime]=useState(0);
 const handleStart=()=>{
    setTime(true);
 }
const handleStop=()=>{
    setTime(false);
 }
 .....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer/>:null}

This was the parent component and the following code is for "timer" component.

import React,{useEffect,useState} from 'react';
const Timer = () => {  
    const[timer,setTimer]=useState(0);
    useEffect(()=>{
        setTimeout(()=>{
            setTimer(prevTime=>prevTime+1);
        },100)
    },[timer])
    let style={
        position:"absolute",
        height:"100px",
        weight:"200px",
        backgroundColor:"red",
        zIndex:"1"
    }
    const handleStopTime=()=>{
        console.log(timer);
        setTimer(0);
    }
    return (
        <div style={style}>
            <h1>{timer}</h1>
        </div>
      );
}

export default Timer;
java-user
  • 21
  • 7

3 Answers3

0

You can pass function as prop to child component.

const Parent = () => {
    const [dataState, updateState] = useState('');

    const handler = (data) => {
        updateState(data)
    }

    return (
         <Child someHandlerProp={handler}/>
    )
}

const Child = (props) => {
    return (
        <button onClick={() => props.someHandlerProp('some data')}>Button</button>
    )
}
Yevhen Kazmirchuk
  • 119
  • 1
  • 1
  • 6
0

You can pass a function to your timer like this:

const[time,setTime]=useState(0);
const[timerValue,setTimerValue]=useState(0);
 const handleStart=()=>{
    setTime(true);
 }
const handleStop=()=>{
    setTime(false);
 }

 .....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer updateTimerValue={setTimerValue}/>:null}

after in you timer you can use this prop to update parent state:

const handleStopTime=()=>{
        console.log(timer);
        props.updateTimer(timer)
        setTimer(0);
    }
B. Mohammad
  • 2,152
  • 1
  • 13
  • 28
0

You can pass a function to a child component which update a value in the the parent component.

Example :

my parent have a variable : name; So i set a function in a parent component as :

updateName = (newValue) => {
    this.setState({
                name: newValue,
            });
    } 

and then i call my child component and give him the function in props, so he can modify this value :

<ChildComponent updateName={this.updateName} />
Imad Salki
  • 416
  • 3
  • 4