I have created a Count down timer component and I have a Button near this component
and I want when users click on this button, resets the timer
and for doing this I should change the child state
I found the solution for changing parent state from the child but I don’t find the solution to this
can it be solved with ref ?? ( my timer component is a functional component )
Advertisement
Answer
React ref forwarding is the solution: This blog will describe more: https://medium.com/javascript-in-plain-english/react-refs-both-class-and-functional-components-76b7bce487b8
JavaScript
x
54
54
1
import React, { useState } from "react";
2
import "./styles.css";
3
4
class ChildClass extends React.Component {
5
constructor(props) {
6
super(props);
7
this.state = {
8
timer: 100
9
};
10
this.resetTimer = this.resetTimer.bind(this);
11
}
12
resetTimer() {
13
this.setState({
14
timer: 0
15
});
16
}
17
render() {
18
let { timer } = this.state;
19
return <span>{timer}</span>;
20
}
21
}
22
23
const ChildFunction = React.forwardRef((props, ref) => {
24
const [timer, setTimer] = useState(100);
25
const resetTimer = () => {
26
setTimer(0);
27
};
28
React.useImperativeHandle(ref, ()=>({
29
resetTimer
30
}));
31
return <span>{timer}</span>;
32
});
33
34
export default function App() {
35
let childClassRef = React.createRef(null);
36
let childFuncRef = React.createRef(null);
37
const resetClassTimer = () => {
38
childClassRef.current.resetTimer();
39
};
40
const resetFuncTimer = () => {
41
childFuncRef.current.resetTimer();
42
};
43
return (
44
<div className="App">
45
<ChildClass ref={childClassRef} />
46
<button onClick={resetClassTimer}>Reset</button>
47
<br/>
48
<ChildFunction ref={childFuncRef} />
49
<button onClick={resetFuncTimer}>Reset</button>
50
</div>
51
);
52
}
53
54
I have added both ref forwarding with class components and functional components. It is same with both React.js and React native.