Creating animated effects using inline styles in React

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.

Answer №1

I finally got the answer I was searching for.

The reason it wasn't working was because of the use of "random naming" in the Material UI makestyles package. So I decided to incorporate the animation source from the makestyles package:

const useStyles = makeStyles({
  root: { ... }, 
  child: {
    ...
    animationName: '$fade',
  },
  '@keyframes fade': {
    '0%': { opacity: '0' }, 
    '100%': { opacity: '1' },
  },
})

I then adjusted the duration and delay in the inline styling like this:

<div
  key={item.x}
  style={{
    animationDuration: `${item.duration}s`,
    animationDelay: `${item.delay}s`,
    animationIterationCount: 'infinite', 
  }}
  className={classes.child}
/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My custom font is not compatible with the browser on my asp.net site

I'm having trouble embedding my own font in my .aspx file. Google Chrome and Firefox don't seem to support the font, while IE does. Can someone please provide guidance on how to successfully embed the font in an asp.net page? Below is my code: ...

Make sure to load the <img> html tag before implementing js masonry for optimal

I am facing an issue with jQuery Masonry as it arranges my 'bricks' immediately without waiting for images to load in. Additionally, I need the images to be responsive so I cannot define their height and width like this: <img src="asas" heigh ...

Tips for preventing Parent Component from Re-rendering after dispatching updated Redux properties?

Good evening everyone, I've encountered an error with one of my components. The error message reads: Cannot update a component (GameBase) while rendering a different component (ExistingGame). To locate the bad setState() call inside... I'm not ...

Prevent users from accessing the verification route in a React application

I am currently developing my first MERN app and focusing on the login and registration functionality. However, I have encountered a problem that I am unable to solve. The issue is related to a verification route that appears when a user registers. I want t ...

The hamburger menu functions properly on the homepage but is not working on the individual about page

The burger menu was causing issues initially due to a simple spelling mistake, which I only noticed later. However, the current issue seems more complex. I am now creating separate pages for different sections of my website, such as About Me, Education, et ...

Issue "Value of type '{}' cannot be assigned to parameter of type 'T | (() => T)'" encountered within a React component containing a type parameter

Currently, I am attempting to achieve the following: function SomeComponent<T>({ children }: PropsType) { const [configuration, setConfiguration] = useState<T>({}) } However, I am encountering this issue: The argument of type '{}&apos ...

Save property using the useState hook

I am working on implementing a sorting function in the child component, where the props are passed in from the parent through an axios call. Should I: Store the prop in the child component's useState? Pass the parent's setState function as a pro ...

Incorporating text overlays on images that are compatible with responsive websites is a top priority for me

This is a piece of HTML code that utilizes bootstrap 3 for design purposes. The challenge faced is related to positioning text over an image. When resizing the browser, the alignment of the text with the background gets disturbed. Assistance is needed in r ...

What is the best method for retrieving the value of a selected option using React hooks?

Here is a snippet of my React Component: const ProductCell = (props) => { const [option, setOption] = useState(); return( <div> <NativeSelect value={option} onChange={e => setOption(e.target.valu ...

Implementing custom styles in JavaScript according to the specific browser or platform

When it comes to adding multiple css styles to a dom element and ensuring compatibility across different browsers, which approach is more optimal for performance? Combining all prefixed css properties together, allowing the browser to decide which one ...

Reload a tab on a one-page site

Imagine clicking a link that leads you to a single-page application. You expect the page to load instantly, as long as you're logged in. The problem arises when the data isn't retrieved from the server, leaving the page blank. What's the b ...

Why React's setState is only returning the last item when a list is saved to a variable

Being a newcomer to React, I am currently working on a small project that involves using the GitHub API to perform a search and display the results on the screen via AJAX. Right now, I am utilizing a for loop to iterate through the response data, saving it ...

Tips for eliminating gaps between navigation items (HTML / CSS)

I'm struggling to eliminate the spacing between the li items in my navigation bar. Even after setting margin: 0px for both the item and anchor (link), the gap still persists. How can I get rid of these spaces? /* navigation styles */ nav { backgroun ...

Using the spread syntax to eliminate a property from an object within a ReactJs element

I'm trying to figure out if it's possible to remove a specific object property using spread syntax when rendering a React component. I want to achieve this without adding too much extra code. Currently, I am utilizing {reset,...inputName} In my ...

Struggling to center a MatIcon within a MatButtonToggle component in an Angular project

I've been struggling to center the MatIcon in the MatButtonToggle, trying multiple methods without success. It may seem like a minor issue, but it's causing quite a bit of trouble for me. Can someone please guide me on how to make this adjustment ...

Determining the best times to utilize Grid items for alignment and justification versus when to avoid using them

I am wondering about the appropriate use of Grid item in order to utilize the props of the Grid container such as justify or alignItems. I initially thought that these attributes could only be applied to the Grid item within the Grid container, but my exam ...

The HTML image link is adorned with a tiny blue checkmark underneath

My a tag with an image inside seems to be extending below the image, resulting in a small blue tic mark on the bottom right side. I've attempted different CSS solutions such as setting border to none, but nothing has resolved the issue. Any assistance ...

Exploring Scroll Functionality for Inner Components Within Mat-tab

I am currently working on a small attendance project that involves using table components within mat-tab elements. However, I am facing an issue where the overflow from the table causes the entire component to scroll, when in fact I only want the table its ...

Adding property to an object retrieved from an API in a React application can be achieved effortlessly by utilizing the useState

How can I implement a toggle functionality for Bookmarked Meals on my Meal Recipe Website available at ? I am currently using the logic to set data.meals[0].bookmarked to true or false, but I want to use setState instead in order to rerender the page when ...

Creating a Triangular Button with Icon Design with Bootstrap 4

I'm attempting to design a CSS triangular button that is positioned in the top left corner of a div using Bootstrap 4. Here's my concept as crafted with Photoshop: https://i.sstatic.net/cbUWL.png However, after numerous attempts, this is the c ...