I have a 100 images in my project and i need to add a class "lazy-img-bg" and an onLoad event that removes the class once image is loaded. Basically, I am displaying a logo while the actual image is loaded in it's place. Is there a way to add this event and class without jquery. The images are in different components.
<img
onLoad={onImageLoadSuccess}
className="lazy-img-bg"
src={}
/>
Create a component that uses state to change the class of the img component, and then display your images using said component.
For example (unloaded image would have a red border):
const { useState } = React;
const Img = ({ src }) => {
const [loaded, setLoaded] = useState(false)
return (
<img
onLoad={() => setLoaded(true)}
className={ loaded ? '' : 'lazy-img-bg'}
src={src}
/>
)
}
ReactDOM.render(
<Img src="https://picsum.photos/200/300" />,
root
)
.lazy-img-bg {
width: 200px;
height: 300px;
border: 2px solid red;
}
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>