Not getting variable in style attribute

Viewed 49

It's difficult to explain, but, here's the thing: When I try to get getFadeContainerKeyFrame in const FadeContainer = ..., everything works. On the other hand, when I try to get the same const from the style attribute in FadeContainer, it does not ... Can someone for the love of god explain this to me? TIA!

import React, { forwardRef } from 'react'
import PropTypes from 'prop-types'
import styled, { keyframes } from 'styled-components'
import styles from '../Header.css'

const getFadeContainerKeyFrame = ({ animatingOut, direction }) => {
  if (!direction) return;
  return keyframes`
  to {
    transform: translateX(0px);
    opacity: ${animatingOut ? 0 : 1};
  }
`
}

const FadeContainer = styled.div`
  animation-name: ${getFadeContainerKeyFrame};        // <- this works ...
`

const propTypes = {
  direction: PropTypes.oneOf(["right", "left"]),
  animatingOut: PropTypes.bool,
  children: PropTypes.node
}


const FadeContents = forwardRef(
  ({ children, animatingOut, direction }, ref) => (
    <FadeContainer
      className={styles.fadeContainer}
      style={{
        animationName: getFadeContainerKeyFrame,       // <- this does not work ...
        opacity: direction && !animatingOut ? 0 : 1,
      }}
      // prevent screen readers from reading out hidden content
      aria-hidden={animatingOut}
      animatingOut={animatingOut}
      direction={direction}
      ref={ref}
    >
      {children}
    </FadeContainer>
  )
)

FadeContents.displayName = 'FadeContents'
FadeContents.propTypes = propTypes

export default FadeContents;
1 Answers

Are you sure you send the valid props to the getFadeContainerKeyFrame function ? If you console.log(animatingOut, direction) inside getFadeContainerKeyFrame, are the props printed ?


Try to do:

const getFadeContainerKeyFrame = (animatingOut, direction) => {
  if (!direction) return;
  return keyframes`
  to {
    transform: translateX(0px);
    opacity: ${animatingOut ? 0 : 1};
  }
`
}

<FadeContainer
  className={styles.fadeContainer}
  style={{
    animationName: getFadeContainerKeyFrame(animatingOut, direction)
    opacity: direction && !animatingOut ? 0 : 1,
  }}
  aria-hidden={animatingOut}
  animatingOut={animatingOut}
  direction={direction}
  ref={ref}
>
  {children}
</FadeContainer>
Related