Skip to content

Instantly share code, notes, and snippets.

@yuvalkarmi
Last active February 9, 2024 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuvalkarmi/215451742b09bcb25498deffe3ebfa9b to your computer and use it in GitHub Desktop.
Save yuvalkarmi/215451742b09bcb25498deffe3ebfa9b to your computer and use it in GitHub Desktop.
// MUI v5 Checkbox with a ripple effect that gets triggered when label is clicked
// Inspired by, and partially adapted from by this excellent StackOverflow answer:
// https://stackoverflow.com/questions/66888248/how-do-i-programatically-show-ripple-effect-with-mui
import { useRef, useState } from 'react';
import { Stack, Checkbox, Typography, Box } from '@mui/material';
import TouchRipple from '@mui/material/ButtonBase/TouchRipple';
const CheckboxWithLabelAndRipple = ({ label, checked, onChange }) => {
const checkboxRef = useRef(null);
const rippleRef = useRef(null);
const [disableRipple, setDisableRipple] = useState(false);
const triggerRipple = () => {
setDisableRipple(true);
const container = checkboxRef.current;
const rect = container.getBoundingClientRect();
rippleRef.current.start(
{
clientX: rect.left + rect.width / 2,
clientY: rect.top + rect.height / 2,
},
{ center: true }, // when center is true, the ripple doesn't travel to the border of the container
);
setTimeout(() => {
rippleRef.current.stop({})
setDisableRipple(false);
}, 150);
};
const handleClick = () => {
triggerRipple();
onChange(!checked);
}
return (
<Stack direction='row' alignItems='center' sx={{ cursor: 'pointer' }} onClick={handleClick}>
<Box sx={{
position: 'relative',
'& .MuiTouchRipple-child': {
backgroundColor: 'primary.main',
}
}} ref={checkboxRef}>
<Checkbox
checked={checked}
// dynamically disabling the ripple effect so that we can maintain the nice hover effect directly on checkbox
disableRipple={disableRipple}
/>
<TouchRipple ref={rippleRef} center />
</Box>
<Typography variant='body2'>{label}</Typography>
</Stack>
);
};
export default CheckboxWithLabelAndRipple;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment