Skip to content
Advertisement

How to change the child state component from parent in functional component

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

import React, { useState } from "react";
import "./styles.css";

class ChildClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timer: 100
    };
    this.resetTimer = this.resetTimer.bind(this);
  }
  resetTimer() {
    this.setState({
      timer: 0
    });
  }
  render() {
    let { timer } = this.state;
    return <span>{timer}</span>;
  }
}

const ChildFunction = React.forwardRef((props, ref) => {
  const [timer, setTimer] = useState(100);
  const resetTimer = () => {
    setTimer(0);
  };
  React.useImperativeHandle(ref, ()=>({
    resetTimer
  }));
  return <span>{timer}</span>;
});

export default function App() {
  let childClassRef = React.createRef(null);
  let childFuncRef = React.createRef(null);
  const resetClassTimer = () => {
    childClassRef.current.resetTimer();
  };
  const resetFuncTimer = () => {
    childFuncRef.current.resetTimer();
  };
  return (
    <div className="App">
      <ChildClass ref={childClassRef} />
      <button onClick={resetClassTimer}>Reset</button>
      <br/>
      <ChildFunction ref={childFuncRef} />
      <button onClick={resetFuncTimer}>Reset</button>
    </div>
  );
}

I have added both ref forwarding with class components and functional components. It is same with both React.js and React native.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement