How to import Json file with React lazy loading?
Asked Answered
S

1

12

I want to implement lazy loading in my React app but most of the files are JSON. Few of them are loading when the viewport width is less than e.g. 768px and I don't want to load them in the Desktop app when they are not needed. Is there any way to load the JSON file with React.lazy()?

My JSON file is generated with Adobe After Effect extensions called: 'Bodymovin' and later I am importing this file like this:

import * as background from './background.json';
import * as backgroundLarge from './background-large.json';
import * as backgroundMedium from './background-medium.json';
import * as backgroundMobile from './background-mobile.json';
import * as backgroundSmallMobile from './background-smallMobile.json';
import * as tree from './tree.json';
import * as treeLarge from './tree-large.json';
import * as treeMedium from './tree-medium.json';
import * as treeMobile from './tree-mobile.json';
import * as treeSmallMobile from './tree-smallMobile.json';

I was trying to load it normally like any other components with default export but it's not working.

const treeMedium = lazy(() => import('./tree-medium.json'));

When I import JSON normally I am using it later like this:

backgroundOptions: {
      loop: true,
      autoplay: true,
      animationData: background.default,
    },

And pass this object into Lottie component from react-lottie

Can I convert it to lazy loading or I am thinking wrong?

Sacker answered 29/11, 2019 at 13:56 Comment(0)
P
24

It's not a React component, so you shouldn't wrap it with a lazy call.
Basically you just need to load it and handle a promise.
Something like:

componentDidMount() {
 import('./tree-medium.json').then(background => {
  this.setState({ background })
 })
}

and then use it somewhere in your render

UPD 2023: using hooks

const [data, setData] = useState(null);
  
useEffect(() => {
  import('./data.json').then(data => {
    setData(data);
  });
}, []);
Prevention answered 29/11, 2019 at 14:33 Comment(1)
As for 2023, let's not forget about use hook: const data = use(import('./data.json'))Alainaalaine

© 2022 - 2024 — McMap. All rights reserved.