Home > OS >  How to optimize equal const?
How to optimize equal const?

Time:09-17

I'm using some animations from react-lottie and I need to call it several times:

import image01 from 'images/lottie/image01.json';
import image02 from 'images/lottie/image02.json';
...

const defaultOptions = {
    loop: true,
    autoplay: true,
    animationData: image01,
    rendererSettings: {
      preserveAspectRatio: 'xMidYMid slice',
    },
  };
  const firstOptions = {
    loop: true,
    autoplay: true,
    animationData: image02,
    rendererSettings: {
      preserveAspectRatio: 'xMidYMid slice',
    },
  };
  const secondOptions = {
    loop: true,
    autoplay: true,
    animationData: image02,
    rendererSettings: {
      preserveAspectRatio: 'xMidYMid slice',
    },
  };
  const last = {
    loop: true,
    autoplay: true,
    animationData: image03,
    rendererSettings: {
      preserveAspectRatio: 'xMidYMid slice',
    },
  };

  return (
          <Lottie options={defaultOptions} height={400} width={400} />

          <Lottie options={firstOptions} height={400} width={400} />

          <Lottie options={secondOptions} height={400} width={400} />

          <Lottie options={last} height={400} width={400} />
  )

Most values are repeated and the only change is the animationData. Can I optimize this and leave the repeated items in one place?

Thanks!

CodePudding user response:

Yes, you can. Basically, you will have to do:

  • Use one default const for all the common information
  • Use the spread operator.
  • Iterate over the list of images

You can change to:

import image01 from 'images/lottie/image01.json';
import image02 from 'images/lottie/image02.json';
import image03 from 'images/lottie/image03.json';
import image04 from 'images/lottie/image04.json';

const baseOptions = {
  loop: true,
  autoplay: true,
  rendererSettings: {
    preserveAspectRatio: 'xMidYMid slice',
  }
}

const imageOptions = [image01, image02, image03, image04].map((image) => ({ ...baseOptions, animationData: image}))

return (
  {imageOptions.map((imageOptions, idx) => <Lottie key={idx} options={imageOptions} height={400} width={400} />)}
)
  • Related