xxxxxxxxxx
// Passing data through property
// When the member becomes 0, the button become disabled
<button
disabled = {this.props.some_member === 0 ? 'disabled' : ''}
>
Click me
</button>
xxxxxxxxxx
import {useState} from 'react';
export default function App() {
const [message, setMessage] = useState('');
const isAnonymous = true;
const handleClick = event => {
event.currentTarget.disabled = true;
console.log('button clicked');
};
return (
<div>
{/* ✅ disable button when input is empty */}
<div>
<input
type="text"
id="message"
name="message"
value={message}
onChange={event => setMessage(event.target.value)}
/>
<button disabled={!message}>Click</button>
</div>
<hr />
{/* ✅ disable button */}
<button disabled={true}>Click</button>
<hr />
{/* ✅ disable button conditionally */}
<button disabled={isAnonymous ? true : false}>Click</button>
<hr />
{/* ✅ disable button after it has been clicked once */}
<button onClick={handleClick}>Click</button>
</div>
);
}
xxxxxxxxxx
// Input field listens to change, updates React's state and re-renders the component.
<input onChange={e => this.setState({ value: e.target.value })} value={this.state.value} />
// Button is disabled when input state is empty.
<button disabled={!this.state.value} />
xxxxxxxxxx
const buttonRef = useRef();
const disableButton = () =>{
buttonRef.current.disabled = true; // this disables the button
}
<button
className="btn btn-primary mt-2"
ref={buttonRef}
onClick={disableButton}
>
Add
</button>
xxxxxxxxxx
import React, { useState } from "react";
const YourComponent = () => {
const [isDisabled, setDisabled] = useState(false);
const handleSubmit = () => {
console.log('Your button was clicked and is now disabled');
setDisabled(true);
}
return (
<button type="button" onClick={handleSubmit} disabled={isDisabled}>
Submit
</button>
);
}
export default YourComponent;
xxxxxxxxxx
import {useRef} from 'react';
let btnRef = useRef();
const onBtnClick = e => {
if(btnRef.current){
btnRef.current.setAttribute("disabled", "disabled");
}
}
<button ref={btnRef} onClick={onBtnClick}>Send</button>
xxxxxxxxxx
import React from 'react';
function App() {
const [isButtonDisabled, setIsButtonDisabled] = React.useState(true);
return (
<div>
<button disabled={isButtonDisabled}>Submit</button>
<button onClick={() => setIsButtonDisabled(prevState => !prevState)}>Toggle</button>
</div>
);
}
export default App;