How can a ref be added to a material-ui Box component in React, using TypeScript? This is important to allow animation libraries like GreenSock / GSAP to animate nodes. Per material-ui docs, using the itemRef will not work because it requires the use of findDOMNode which is deprecated in strict mode (prep for concurrent React) and further is likely to break due to virtual DOM rendering.
Typescript/React: How can a ref be added to a material-ui Box component?
Asked Answered
Can you provide some coding sample that may emphasize what you are trying to do? –
Biting
@MEDZ, thanks for the response. I have found several other posts on the Box ref limitation, posted on each, and provided a summary with a workaround, below. –
Stephen
Specify setting in title –
Broomstick
Without the ability to associate a ref to ALL MATERIAL-UI GENERATED NODES, there is not a reliable way to integrate animation libraries targeting specific nodes.
There are several related issues on the material-ui GitHub project. I posted a workaround on Issue #17010 until such time as material-ui includes the ability to add ref to all generated nodes.
Related Issues:
- How can a ref be added to a Box component? #19284
- [Box] Allow ref on Box #19275
- ref missing from Box in TypeScript definition #17010
Interim Workaround:
// 1. Import style library, either Emotion or Styled-Components
import styled from "@emotion/styled";
// 2. Recreate the Material-UI Box with a styled component
const StyledBox = styled(Box)``;
// 3. Usage in the render
<StyledBox ref={boxRef}>Box Content</StyledBox>
NOTE: Using @material-ui/core/styles does not work, requiring the use of emotion or styled-components. We are forced to use emotion over styled-components due to an animation flicker problem uniquely generated by styled-components.
It looks like this is fixed in material-ui v5, which is in alpha. –
Reynaud
© 2022 - 2024 — McMap. All rights reserved.