javascriptreactjslottiebodymovin

Dynamic import files with React


I am creating an animations using Adobe After Effects and React Lottie and I have many json files generated by Bodymovin extension. I am importing files in that way:

import * as initial from './white_bird.json';
import * as hoverOn from './white_bird_hover_on.json';
import * as hoverOff from './white_bird_hover_off.json';

But, when I have e.g. 6 other components that look identically but differ from each other only with imported files. How can I write those lines upper in something like this:

const data = {
    initial: import * as initial(`./${some_param}.json`),
  };

Note that I must import it like '* as' in another way this doesn't work


Solution

  • You could use Dynamic import:

    useEffect(() => {
      async loadData() {
        const data = await import(`./${some_param}.json`);
        setInitial(data);
      }
    
      loadData();
    }, [])
    

    and use Promise.all if you have multiple requests:

    useEffect(() => {
      async loadData() {
        const [initalData, hoverOnData, hoverOffData] = await Promise.all([
          import(`./${bird}.json`),
          import(`./${bird}_hover_on.json`),
          import(`./${bird}_hover_off.json`)
        ]);
    
        setInitial(initalData);
        setHoverOn(hoverOnData);
        setHoverOff(hoverOffData);
      }
    
      loadData();
    }, [])