Search code examples
javascriptreactjsarraysconstants

How can I extract a 'const' that depends on a map?


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?


Solution

  • 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>
    ))}