Home > Software engineering >  How to perform multiple onClick React actions?
How to perform multiple onClick React actions?

Time:08-16

All of these options don't work. Please tell me how to perform 2 actions onClick React

<div className='button' onClick={ ()=> alert('1'); alert('2')} > </div>

<div className='button' onClick={ ()=> alert('1'), alert('2')} > </div>

<div className='button' onClick={ ()=> alert('1'), ()=> alert('2')} > </div>

CodePudding user response:

You have to wrap your actions in a block i.e. curly brackets {}. Like this:

<div
  className='button'
  onClick={() => {
    alert('1');
    alert('2');
  }}>

</div>

CodePudding user response:

Try like this, Add your actions in curly braces.

<div className='button' onClick={ ()=> { alert('1'); alert('2') }} > </div>

CodePudding user response:

In addition to the answers of Irfanullah and Pryien, I would like to add that you could wrap it in a helper function and then call the helper function in your JSX code

const handleClick = () => {
   alert("1");
   alert("2");
}

return (
  <div  
     className='button'
     onClick={handleClick}
  >
  </div>
);

  • Related