el solo lobo
el solo lobo

Reputation: 993

If true set attribute else set className in JSX

I have a button in my Component, that should be disabled if the item status is accepted, otherwise bootstrap success class should be appended.

The Problem I´m facing here is that disabled is not a className rather than an attribute and bootstrap btn btn-success is a className.

If it is just about classNames I have no problems with that like here

className={items.status === 'declined' ? 'danger' : 'success'}>

But this results in an error and I have currently no clue how to do that.

 {items.status === 'accepted' ? 'disabled' : 'className=btn btn-success'}

I have also done some research previously, but that didn´t helped me. React.js Disable button

Can someone point me in the right direction here? How can I write a JSX shorthand if-else when true is an attribute and false a className?

Thanks in advance!

Upvotes: 3

Views: 1025

Answers (2)

Serhii Baraniuk
Serhii Baraniuk

Reputation: 3375

class Example extends React.Component {
  render() {
    const disabled = true
    const className = true === 'declined' ? 'danger' : 'success'
    return (
      <button disabled={disabled} className={className}>
        Example
      </button>
    )
  }
}

ReactDOM.render(
  <Example />,
  document.getElementById('app')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app" />

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77482

You should set both attributes className and disabled

const isAccepted    = items.status === 'accepted';
const buttonClasses = isAccepted ? '<some class>' : '<another class>'

<button 
   className={ buttonClasses }
   disabled={ isAccepted }
>
  Button
</button>

Upvotes: 4

Related Questions