Sean D
Sean D

Reputation: 4292

MUI Fade component does not show, hide, or fade components

I switched child components from conditional rendering to being wrapped by <Fade /> but Fade doesn't work at all, both components always display. Here is the current code:

// inside top level component
{/*{adminView === bodyViews.addNewCoupon &&*/}
<Fade
  in={Boolean(adminView === bodyViews.addNewCoupon)}
  timeout={2000}
>
  <AddCouponForm />
</Fade>
{/*}*/}
  
{/*{adminView === bodyViews.viewCurrentCoupons &&*/}
<Fade
  in={Boolean(adminView === bodyViews.viewCurrentCoupons)}
  timeout={2000}
>
  <ViewCoupons />
</Fade>
{/*}*/}

Based on the API here. I believe in set to true should cause the component to fade in. This worked for causing a conditional render in the commented out unary but does not seem to work within the in value. What mistake is being made?

Update

When I comment the custom components and inserting something like <p>Section 1/2</p> then the fade works. Something about the custom compoonents must cause the fade not to work

Upvotes: 12

Views: 11871

Answers (2)

NearHuscarl
NearHuscarl

Reputation: 81520

Fade updates the child component via the styles prop, if you're using a custom component you need to forward the ref to the child and make sure the props from Fade are passed down:

const MyComponent = React.forwardRef((props, ref) => {
  return (
    <div {...props} ref={ref}>
      my component
    </div>
  );
});
<Fade in={checked}>
  <MyComponent />
</Fade>

Live Demo

Codesandbox Demo

Upvotes: 7

Sean D
Sean D

Reputation: 4292

The issue was traced specifically back to Custom components: they don't seem to work as direct children of <Fade />. Issue is solved by wrapping the custom component children in a div.

  <Fade
    in={ Boolean(adminView === bodyViews.addNewCoupon) }
    timeout={ 4000 }
  >
    <div>
      <AddCouponForm />
    </div>
  </Fade>     

  <Fade
    in={ Boolean(adminView === bodyViews.viewCurrentCoupons) }
    timeout={ 4000 }
  >
    <div>
      <p>Section 2</p>
      <ViewCoupons />
    </div>
  </Fade>

As a side note, Fade also seems to have issues with more than one child. Therefore all children should go inside a single div element.

Upvotes: 30

Related Questions