Home > Software engineering >  How to extract a const that depends on a map?
How to extract a const that depends on a map?

Time:09-19

I have animations in my component that follow the same style, like this:

{actions.map((action, i) => (
    <Component style={{ animation: `fade-animation 12s linear ${i * 3}s infinite` }}>{action}</Component>
))}

{figures.map((figure, i) => (
    <Component style={{ animation: `fade-animation 12s linear ${i * 3}s infinite` }}>{figure}</Component>
))}

The value fade-animation 12s linear ${i * 3}s infinite it's being repeated in multiple places.

How can I extract this into a const?

I tried:

const fadeAnimation = `fade-animation 12s linear ${i * 3}s infinite`;

But as the i depends on the map, it causes an error.

Can I extract this even with the i?

Thanks!!

CodePudding user response:

const fadeAnimation = (time) => `fade-animation 12s linear ${time * 3}s infinite`;

Use it like this:

{figures.map((figure, i) => (
    <Component style={{ animation: fadeAnimation(i) }}>{figure}</Component>
))}

CodePudding user response:

const fadeAnimation = (i) => `fade-animation 12s linear ${i * 3}s infinite`;

usage:

{figures.map((figure, i) => (
  <Component style={{ animation: fadeAnimation(i) }}>{figure}</Component>
))}

CodePudding user response:

Things to try:

This follows the Inversion of Control style.

const fadeAnimation = duration => `fade-animation 12s linear ${duration}s infinite`;

{figures.map((figure, i) => (
    <Component style={{ animation: fadeAnimation(3 * i) }}>{figure}</Component>
))}

This follows Default Value style.

const fadeAnimation = "fade-animation 12s linear infinite";

{figures.map((figure, i) => (
    <Component style={{ animation: `${fadeAnimation} ${i * 3}s` }}>{figure}</Component>
  • Related