-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; 
1
  • No, but the following anwers did. Commented Jun 1, 2020 at 14:37

3 Answers 3

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> ) } 
Sign up to request clarification or add additional context in comments.

Comments

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); } 

1 Comment

Your answer wasn't clear enough but I Solved it using one of the following answers.
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} /> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.