3

I want to show loader till the time image get loads. I tried but it's not working.

const showLoader = () => {
    return (
      <div className="border-2">
        <Loader />
      </div>
    );
  };

 <img
 className="w-full"
 src={item?.image}
 onClick={() => setId(item?.id)}
 onLoad={() => showLoader()}
  />

1
  • onLoad is called after the image gets loaded Commented Aug 17, 2021 at 15:09

1 Answer 1

12

The onLoad event will be triggered once the image is loaded - https://idiallo.com/javascript/img-detect-loaded

NOTE - Do not conditionally render the img tag. The onLoad event will not be triggered if the img tag does not exist in the DOM. Rather, use the display property to set the loading state

Try this -

function Test() {
  const [loading, setLoading] = useState(true);

  return <>
    <div style={{display: loading ? "block" : "none"}}>
       {showLoader()}
    </div>
    <div style={{display: loading ? "none" : "block"}}>
        <img 
          className="w-full"
          src={item?.image}
          onClick={() => setId(item?.id)}
          onLoad={() => setLoading(false)} />
    </div>
  </>;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.