Source:  Twitter logo

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.

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.

3 users liked answer #0dislike answer #03
n8sabes profile pic
n8sabes

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).