4

I'm trying to do a ternary as you can see below (not working) and surprised to find there isn't a SO answer that I can find. What's the right way of doing a ternary for an attribute inside html tags in react? I just want required to be added if id == 1

import React from 'react'

const Word = ({onRemoveWord, id, onChangeWord}) => {
  return (
    <div>
       <input 
          type="text" 
          { id === 1 ? required : null}
          name="word" 
          id={id} 
          onChange={(e) => {onChangeWord(e)}} 
        /> 
        <span onClick={() => {onRemoveWord(id)}} className="deletebtn">-</span>
    </div>
  )
}

export default Word
AGrush
  • 1,107
  • 13
  • 32

1 Answers1

4

As @jonrsharpe mentiond above,

<input 
    type="text" 
    required={id===1}
    name="word" 
    id={id} 
    onChange={(e) => {onChangeWord(e)}} 
/> 

If you need to add another attribute based on id, you can add like below.

<button className={id===1 ? "primary" : "second"}>
    MyButton
</button>
Kid
  • 1,160
  • 2
  • 14
  • 31
  • this works!.. so does this mean required=0 and required=1 turn off and on the required functionality? – AGrush Apr 23 '20 at 10:08
  • 1
    from the linked article.. "Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy." woah – AGrush Apr 23 '20 at 10:11