Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary inside input react [duplicate]

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
like image 293
AGrush Avatar asked Oct 18 '25 16:10

AGrush


1 Answers

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>
like image 67
Kid Avatar answered Oct 20 '25 07:10

Kid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!