Ong Yu Feng
Ong Yu Feng

Reputation: 21

How to disable button based on state of other button

I'm trying to create 2 buttons in react app using material ui buttons with both buttons are enabled at the start of page load. When onClick on one of the button, the other button should be disabled vice versa.

Initial state

When onClick

const [btn1, setBtn1] = useState(false);
const [btn2, setBtn2] = useState(false);

const onBtn1 = () => {
        setBtn1(!btn1);
    };

    const onBtn2 = () => {
        setBtn2(!btn2);
    };
}

How do i go about doing it? is there anyway to just use a single useState hook to handle 2 state buttons?

Upvotes: 0

Views: 942

Answers (4)

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7166

You can achieve this with only one state variable and one function

Code

const [disabledButton, setDisabledButton] = useState('');      

const onButtonClick = (param) => {
  setDisabledButton(param);
}    

<Button onClick={() => onButtonClick('btn2')} disabled={disabledButton === 'btn1'}>
   Button 1
</Button>
<Button onClick={() => onButtonClick('btn1')} disabled={disabledButton === 'btn2'}>
   Button 2
</Button>

Upvotes: 1

navintellis
navintellis

Reputation: 59

you can use a single state, please refer the suggestion below:

state and event handlers-

const [activeButton, setActiveButton] = useState("None");


const onBtn1 = () => {
        setActiveButton("Button1");
    };


const onBtn2 = () => {
        setActiveButton("Button2");
    };

HTML Element part -

<Button disabled={!['None', 'Button1'].includes(activeButton)}>Button1</Button>
<Button disabled={!['None', 'Button2'].includes(activeButton)}>Button2</Button>

Upvotes: 0

TechySharnav
TechySharnav

Reputation: 5094

Change the state of other button on press.

const [btn1, setBtn1] = useState(true);  //Initially both buttons are enabled
const [btn2, setBtn2] = useState(true);

const onBtn1 = () => {
        setBtn1(!btn1);
        setBtn2(false);
    };

    const onBtn2 = () => {
        setBtn2(!btn2);
        setBtn1(false);
    };
}

Upvotes: 0

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

You can just enable the other button when a button is clicked:

const onBtn1 = () => {
   setBtn1(prevState => !prevState);
   setBtn2(false);
};

const onBtn2 = () => {
   setBtn2(prevState => !prevState);
   setBtn1(false);
};

in the JSX:

<button onClick={onBtn1} disabled={btn1}>btn1</button>
<button onClick={onBtn2} disabled={btn2}>btn2</button>

Upvotes: 0

Related Questions