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
5
  • 1
    What's the output you're expecting? If you're trying to conditionally set an attribute, did you want required={id === 1}?
    – jonrsharpe
    Commented Apr 23, 2020 at 10:04
  • 1
    What's your desired result?
    – Kid
    Commented Apr 23, 2020 at 10:05
  • 1
    I think he wants the required attribute if id === 1, and no such attribute otherwise Commented Apr 23, 2020 at 10:05
  • 1
    your attribute should look like <input required={ id === 1}/> Commented Apr 23, 2020 at 10:07
  • 2
    Then see e.g. stackoverflow.com/q/31163693/3001761, you don't need a ternary.
    – jonrsharpe
    Commented Apr 23, 2020 at 10:08

1 Answer 1

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>
2
  • this works!.. so does this mean required=0 and required=1 turn off and on the required functionality?
    – AGrush
    Commented Apr 23, 2020 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
    Commented Apr 23, 2020 at 10:11

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.