Home > Net >  Using forwardRef & useImperativeHandle to trigger child functions from parent
Using forwardRef & useImperativeHandle to trigger child functions from parent

Time:08-22

I am trying to trigger two functions from a parent component by using forwardRef & useImperativeHandle. My code is below. I am not sure where I am going wrong but my code is failing to compile with the errors below. Please can someone advise? I thought i have defined the two functions in question that the compiler is complaining about. have I got the syntax wrong?

  const SimpleBackdrop = React.forwardRef((props, ref) => {
  const [open, setOpen] = React.useState(false);
  React.useImperativeHandle(ref, () => ({
    handleClose() {
      setOpen(false);
    },
    handleToggle() {
      setOpen(!open);
    },
  }));

  return (
    <div>
      <Button onClick={handleToggle}>Show backdrop</Button>
      <Backdrop
        sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer   1 }}
        open={open}
        onClick={handleClose}
      >
        <CircularProgress color="inherit" />
      </Backdrop>
    </div>
  );
});

export default SimpleBackdrop;

I am getting the following error in the console:

Failed to compile.

[eslint] 
src/components/myApp/SimpleBackdrop.js
  Line 44:24:  'handleToggle' is not defined  no-undef
  Line 48:18:  'handleClose' is not defined   no-undef

I have alos tried to re-write is as below, but still getting the same compile error:

import * as React from 'react';
import Backdrop from '@mui/material/Backdrop';
import CircularProgress from '@mui/material/CircularProgress';
import Button from '@mui/material/Button';

const SimpleBackdrop = (props, ref) => {
  const [open, setOpen] = React.useState(false);

  React.useImperativeHandle(ref, () => ({
    handleClose: () => setOpen(false),
    handleToggle: () => setOpen(!open)
  }));

  return (
    <div>
      <Button onClick={handleToggle}>Show backdrop</Button>
      <Backdrop
        sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer   1 }}
        open={open}
        onClick={handleClose}
      >
        <CircularProgress color="inherit" />
      </Backdrop>
    </div>
  );
}

export default React.forwardRef(SimpleBackdrop);

CodePudding user response:

Try this:

const SimpleBackdrop = React.forwardRef(({...props}, ref) => {
  const [open, setOpen] = React.useState(false);

  const handleClose = () => {
    setOpen(false);
  }; 

  const handleToggle = () => {
    setOpen(!open);
  };

  React.useImperativeHandle(ref, () => ({
    handleClose, handleToggle 
  }));

  return (
    <div>
      <Button onClick={handleToggle}>Show backdrop</Button>
      <Backdrop
        sx={{ color: '#fff', zIndex: (theme) => theme.zIndex.drawer   1 }}
        open={open}
        onClick={handleClose}
      >
        <CircularProgress color="inherit" />
      </Backdrop>
    </div>
  );
});

export default SimpleBackdrop;
  • Related