Ad
React OnLoad Event On Image Tag Is Not Getting Called When Using Conditional Render
I'm using the stateless functional component to add spinner while image is loading from the external resource, like so:
function ExternalImage(props) {
const [loaded, setLoaded] = useState(false);
function onLoad() {
console.log('loaded');
setLoaded(true);
}
return loaded
? <img
onLoad={onLoad}
src={props.src}
alt={props.alt}
{...props}
/>
: <Spin />
}
And use it like so:
<ExternalImage src={image.src} alt={image.alt} className="image" />
Why would the onLoad
never get called?
Ad
Answer
When image is not loaded you aren't actually rendering the image. You need to render it for its onLoad to fire
function ExternalImage(props) {
const [loaded, setLoaded] = useState(false);
function onLoad() {
console.log('loaded');
setLoaded(true);
}
return (
<>
<img
style={{display: loaded? 'block': 'none'}}
onLoad={onLoad}
src={props.src}
alt={props.alt}
{...props}
/>
{!loaded && <Spin /> }
</>
)
}
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad