Animate background using Framer Motion

Viewed 1266

I'm trying to create a React component where when scrolling down into it, its background transitions from a color to an image.

This is the component:

const TeamSection = () => {
    return (
        <Background>
            <TeamSectionContainer
                initial={{
                    opacity: 0,
                }}
                whileInView={{
                    opacity: 1,
                }}
                transition={{
                    ease: "easeOut",
                    duration: 2,
                }}
            >
                <Title>Text</Title>
                <Team>Text<Team>
            </TeamSectionContainer>
        </Background>
    );
};

And the styles:

const TeamSectionContainer = styled(motion.div)`
    ${tw`
        bg-no-repeat
        w-full
        min-h-[200vh]
        flex
        flex-col
    `};
    background-image: url(${BackgroundImage});
`;

const Background = tw.div`
    bg-[#001F33]
`;

The result is that th animation works for the whole TeamSectionContainer component, indluding its background. I'm trying to make it so that none of the content is animated and only the background is.

How could be this achieved?

1 Answers

I don't think you can animate the opacity of a background image like that. You'd need to add a separate div inside the TeamSectionContainer with the background image and apply the animation to that:

const TeamSection = () => {
    return (
        <Background>
            <TeamSectionContainer>
                <motion.div className="backgroundImage"
                    initial={{
                        opacity: 0,
                    }}
                    whileInView={{
                        opacity: 1,
                    }}
                    transition={{
                        ease: "easeOut",
                        duration: 2,
                    }}
                />
                <Title>Text</Title>
                <Team>Text<Team>
            </TeamSectionContainer>
        </Background>
    );
};

Related