javascriptreactjsecmascript-6

How to add disabled attribute via prop to a button in react?


I am creating a custom button component in react. I want to pass a prop to that button, based on the value of which button gets enabled or disabled.

My problem is - The mere presence of the disabled property disables the element, so I cannot set its value as "false". Even the following code is disabling the element

<input type="button" id="myBtn" value="Submit" disabled="" />

I need to either remove the attribute completely or set its property via javascript.

document.getElementById("myBtn").disabled = true;

My custom button component is -

import React from 'react';

const CustomButton = ({ whenClicked, classNames, buttonText, isDisabled }) =>
    (
        <button
            onClick   = {whenClicked}
            className = {`btn ${classNames}`}
            type      = "button"
            disabled  = {isDisabled}
        >
           {buttonText}
        </button>
    );

export default CustomButton;

isDisabled is a boolean value.

One more thing, I lost the default submit behavior of button while using custom button. Now I always need to pass a click handler. Is there any way to achieve the same behavior again?


Solution

  • What you currently have should work perfectly fine. Be careful that when you use CustomButton you don't send in the value for disabled as a string. That will make it disabled regardless of what you pass in. Instead, you need to pass in a boolean, that's in JSX syntax.

    Here's a sample usage where you would put it inside of a render function of a component that uses the button:

    ...
    render() {
        <div>
            ...
            <CustomButton
                whenClicked={() => console.log('I just got clicked')}
                buttonText="Some Button"
                isDisabled={false}
            />
            ...
        </div>
       }
    ...
    

    Basically, instead of false you could pass in something else. You could pass in a boolean value that's stored on the props of the container that holds the CustomButton.

    You could say isDisabled={this.props.disableInnerButton} and it would work as you would expect. Changing the value of the boolean will disable or enable the button.

    Below you can find a relevant answer I gave recently on a very similar topic:

    Statement to add or not an attribute in JSX