htmlreactjsreact-props

How to add disabled attribute to button in react?


Here is my code

import React from 'react'
import PropTypes from "prop-types";

export default function Button({ htmlType, type, disabled, action, ...props}) {
  return (
    <button type={htmlType} onClick={action}>
        {props.children}
    </button>
  )
}

Button.propTypes = {
    htmlType: PropTypes.string.isRequired,
    action: PropTypes.func,
    disabled: PropTypes.bool
};

I call Button component by this code

 <Button disabled={true}>button title</Button>

I want to add disabled html attribute to button when disabled of props is true, how to do it ?


Solution

  • You could line single line if-else statements like this:

    <button disabled={propsDisabled}>button title</button>
    

    Here, propsDisabled is the variable which you can pass through the props, and it is a boolean variable which will either be true or false. I have not used disabled itself to avoid confusion but you can use the variable name as disabled.

    When propsDisabled is true, the button will be disabled, and when propsDisabled is false the button will not be disabled.