Home > Software engineering >  onLoad event in React not behaving as I would expect
onLoad event in React not behaving as I would expect

Time:10-30

I have the following component:

const testLog = () => {   
    console.log('aaa - test') ;
}

const MyComponent = () => (
    <img onl oad={() => testLog()} />    
);

I then reference the component in my main app:

<MyComponent />

I can see that the component definitely appears on the screen - I can see the image component, however, the issue I have is that the log message never fires.

At first, I thought I'd maybe need to bind it, so tried this:

const MyComponent = () => (
    <img onl oad={() => this.testLog.bind(this)} />    
);

But it then just tells me that testLog is not used.

CodePudding user response:

In order for onLoad to fire. You need the img to have src. Looking at the code you provided, the img tag has nothing to load.

CodePudding user response:

Try to use useEffect hook, please https://reactjs.org/docs/hooks-effect.html

useEffect(()=>{
  // TODO: your code here
  this.testLog.bind(this)
},[]);
  • Related