skip to Main Content

I have an anchor tags with some attributes but I need to add an attribute based on some attribute.
For example –

     <a
        
        className={someName}
        onContextMenu={handleClick}
      >

I need onContextMenu to be present only if some condition is true. Something like this –

     <a
        
        className={someName}
        if (true) ? onContextMenu={handleClick} : ''
      >

How can I achieve it? Coding in Typescript.

2

Answers


  1. Close. Try
    onContextMenu={true ? handleClick : null}

    Login or Signup to reply.
  2. You can either move your boolean logic into the assignment of the property:

    <a onContextMenu={true ? handleClick : null} />
    

    or you could potentially move the boolean logic into the event handler itself

    const handleClick = (e) => {
      if(!true) return;
    
      // Do other stuff
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search