I am facing a challenge with my component, where I need to implement different animations for each of its children elements. I am currently utilizing React Hooks and Material UI for styling purposes in my project.
The structure of my component(s) is shown below:
const useStyles = makeStyles({ // imported from Material UI
root: {
position: 'relative',
},
child: {
position: 'absolute',
},
})
const Children = (props) => {
const { count } = props;
const classes = useStyles();
const elements = [];
// Generating random values for each child.
for (let i = 0; i < count; i += 1){
const randomX = Math.random() * 100;
const randomY = Math.random() * 100;
... other random variables
const delay = Math.random(); // To be used in animation
const duration = Math.random() * (3 - 0.5) + 0.5; // To be used in animation
elements.push({ ... all random variables mapped });
}
return (
<>
{elements.map(item => {
<div
key={item.x}
style={{
top: `${item.x}`,
left: `${item.y}`,
color: `${item.color}`,
... and more styling properties
}}
className={classes.child}
/>
}
</>
);
};
const Parent = () => {
const classes = useStyles();
return (
<div className={classes.root}>
<Children count={5} />
</div>
);
};
My current issue revolves around the desire to have distinct animations for each child element triggered based on specific parameters. I experimented with incorporating keyframe animations within the makeStyles styling section, which worked when defining it globally. However, individualizing the animation parameters for each child element poses difficulties in this approach.
const useStyles = makeStyles({
root: { ... },
child: {
...
animation: '$fade 2s 1s infinite', // The challenge lies in customizing duration and delay for each child
},
'@keyframes fade': {
'0%': { opacity: '0' },
'100%': { opacity: '1' },
},
})
I also attempted including the keyframe animation in the inline styling of the child component but encountered issues with its functionality.
<div
key={item.x}
style={{
top: `${item.x}`,
left: `${item.y}`,
color: `${item.color}`,
... and additional properties
animation: `fade ${item.duration} ${item.delay} infinite`, // This approach failed even with static values
}}
className={classes.child}
/>
I am reaching out here seeking guidance on how to address this dilemma. I believe that solutions might exist through 'StyledComponents', yet I am hesitant to introduce another styling library solely for this unique issue.
In past experiences, I recall working with CSS custom variables var(--duration)
and var(--delay)
, which offered versatility in handling similar challenges. Nonetheless, current resources have not provided actionable insights on effectively integrating these custom variables into my styling setup. If you possess knowledge on the ideal configuration for this scenario, please share your input.
Thank you in advance for any assistance you can provide.