-
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
63 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import React from 'react'; | ||
import useImageOnload from './useImageOnload'; | ||
|
||
function Learn_3() { | ||
const imageUrl = | ||
'https://res.cloudinary.com/ecommerce2021/image/upload/v1663398918/profile-forme/avatar_ws0jhh.png'; | ||
const [loaded, error] = useImageOnload(imageUrl); | ||
|
||
return ( | ||
<div> | ||
{error && <p>{error}</p>} | ||
{loaded ? ( | ||
<img src={imageUrl} alt="Loaded Image" style={{ width: '50%' }} /> | ||
) : ( | ||
<p>Loading...</p> | ||
)} | ||
</div> | ||
); | ||
} | ||
|
||
export default Learn_3; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import { useState, useEffect } from 'react'; | ||
|
||
function useImageOnload(src) { | ||
const [loaded, setLoaded] = useState(false); | ||
const [error, setError] = useState(null); | ||
|
||
useEffect(() => { | ||
const image = new Image(); | ||
|
||
const handleLoad = () => { | ||
setLoaded(true); | ||
setError(null); | ||
}; | ||
|
||
const handleError = () => { | ||
setLoaded(false); | ||
setError('Error loading image'); | ||
}; | ||
|
||
image.addEventListener('load', handleLoad); | ||
image.addEventListener('error', handleError); | ||
|
||
// Bắt đầu tải hình ảnh khi src thay đổi | ||
image.src = src; | ||
|
||
// Hủy bỏ event listeners khi component bị unmount | ||
return () => { | ||
image.removeEventListener('load', handleLoad); | ||
image.removeEventListener('error', handleError); | ||
}; | ||
}, [src]); | ||
|
||
return [loaded, error]; | ||
} | ||
|
||
export default useImageOnload; |