Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
How to programmatically add a className and a onLoad function to all the images in the project at once in React app without Jqyery

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={}
    /> 
    

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!