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?
import React from "react"; import { lazyLoader } from "./lazyLoader"; const Customer = lazyLoader(() => import("./Customer. js")); const Admin = lazyLoader(() => import("./Admin. js")); //Instead of regular import statements, we will use the above approach for lazy loading export default (props) => { if (props.
Use the json-loader to Import JSON File in React config . By adding json-loader in webpack. config helps us to avoid adding a json-loader in each file. Once we have added JSON loader in loaders, we can import it.
Take any component that you want to lazy load and change it to the following: - import MyComponent from './MyComponent'; + const MyComponent = React. lazy(() => import('./MyComponent')); You can do the same for library components as well.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With