score:178
Using refs
is not best practice because it reads the DOM directly, it's better to use React's state
instead. Also, your button doesn't change because the component is not re-rendered and stays in its initial state.
You can use setState
together with an onChange
event listener to render the component again every time the input field changes:
// 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} />
Here's a working example:
class AddItem extends React.Component {
constructor() {
super();
this.state = { value: '' };
this.onChange = this.onChange.bind(this);
this.add = this.add.bind(this);
}
add() {
this.props.onButtonClick(this.state.value);
this.setState({ value: '' });
}
onChange(e) {
this.setState({ value: e.target.value });
}
render() {
return (
<div className="add-item">
<input
type="text"
className="add-item__input"
value={this.state.value}
onChange={this.onChange}
placeholder={this.props.placeholder}
/>
<button
disabled={!this.state.value}
className="add-item__button"
onClick={this.add}
>
Add
</button>
</div>
);
}
}
ReactDOM.render(
<AddItem placeholder="Value" onButtonClick={v => console.log(v)} />,
document.getElementById('View')
);
<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='View'></div>
score:-2
just Add:
<button disabled={this.input.value?"true":""} className="add-item__button" onClick={this.add.bind(this)}>Add</button>
score:1
I have had a similar problem, turns out we don't need hooks to do these, we can make an conditional render and it will still work fine.
<Button
type="submit"
disabled={
name === "" || email === "" || password === "" ? true : false
}
fullWidth
variant="contained"
color="primary"
className={classes.submit}>
SignUP
</Button>
score:2
this.input
is undefined until the ref
callback is called. Try setting this.input
to some initial value in your constructor.
From the React docs on refs, emphasis mine:
the callback will be executed immediately after the component is mounted or unmounted
score:3
very simple solution for this is by using useRef
hook
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>
Similarly you can enable the button by using buttonRef.current.disabled = false
score:6
You shouldn't be setting the value of the input through refs.
Take a look at the documentation for controlled form components here - https://facebook.github.io/react/docs/forms.html#controlled-components
In a nutshell
<input value={this.state.value} onChange={(e) => this.setState({value: e.target.value})} />
Then you will be able to control the disabled state by using disabled={!this.state.value}
score:6
There are few typical methods how we control components render in React.
But, I haven't used any of these in here, I just used the ref's to namespace underlying children to the component.
class AddItem extends React.Component {
change(e) {
if ("" != e.target.value) {
this.button.disabled = false;
} else {
this.button.disabled = true;
}
}
add(e) {
console.log(this.input.value);
this.input.value = '';
this.button.disabled = true;
}
render() {
return (
<div className="add-item">
<input type="text" className = "add-item__input" ref = {(input) => this.input=input} onChange = {this.change.bind(this)} />
<button className="add-item__button"
onClick= {this.add.bind(this)}
ref={(button) => this.button=button}>Add
</button>
</div>
);
}
}
ReactDOM.render(<AddItem / > , document.getElementById('root'));
<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="root"></div>
score:7
Here is a functional component variety using react hooks.
The example code I provided should be generic enough for modification with the specific use-case or for anyone searching "How to disable a button in React" who landed here.
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;
score:24
In HTML,
<button disabled/>
<buttton disabled="true">
<buttton disabled="false">
<buttton disabled="21">
All of them boils down to disabled="true" that is because it returns true for a non-empty string. Hence, in order to return false, pass a empty string in a conditional statement like this.input.value?"true":"".
render() {
return (
<div className="add-item">
<input type="text" className="add-item__input" ref={(input) => this.input = input} placeholder={this.props.placeholder} />
<button disabled={this.input.value?"true":""} className="add-item__button" onClick={this.add.bind(this)}>Add</button>
</div>
);
}
Source: stackoverflow.com
Related Query
- How I can disable a button in React js for 5 seconds after click event
- How to disable a button in React Native after clicking it
- How to disable react button until Meteor Method finishes
- How to disable a button from react component inherited by a child react component?
- How to disable button according to input length by using React useState?
- How to disable only selected button onClick inside .map() function of REACT js
- How to disable a button when the state or the input value gets changed in React JS?
- how to disable a button if more than one or no checkbox is checked in React JS
- How to disable a React button conditionally on a state value?
- how to disable radio button in react
- How to disable a button when state changes in React
- how to disable a button if more than once check box is checked in React JS
- How to disable a button using React useState hook inside event handler
- React JS, how can I disable an individual button in a mapped list?
- How do I disable a button in React for just one option if the button is a reusable React component?
- How to Disable button Of an Item In an array onClick React
- React how to disable submit button until form values are input
- How to disable views button in StaticDatePicker in React MUI v5.2.2?
- How I can disable a button in React js for 20 seconds after click
- How to disable specific button in react
- How can I disable back button in React Router?
- React : How to disable button when my function return me a specific value
- how to disable button when clicked in react js for quiz
- How to disable a button when an input is empty?
- How to disable button in React.js
- Disable back button in react navigation
- How to disable source maps for React JS Application
- How to make a Material UI react Button act as a react-router-dom Link?
- How to navigate on path by button click in react router v4?
- How to add a button in React Native?
More Query from same tag
- Pass variable from one component to another ReactJS
- Correct type to set for a renderAs Propery in Typescript React Components?
- How to rerender the parent route from child route reactjs?
- MongoDB not getting delete request
- How to solve TypeError: Cannot read property 'map' of undefined problem in react?
- How can I selectively delete dynamically added input fields in React?
- How can I update model In Show component
- Reusability with Styled-Components in React
- React onchange event: this.setState() not setting state?
- Setting ES6 default arguments to handle empty strings
- What is the React way to the 'Single Item'?
- Trying to reformat this class into a function
- UnhandledPromiseRejection when trying to write to file using API in node
- React and SetInterval (FCC Pomodoro Timer..)
- Auto guess Profit/Loss from django and react
- Can i set default Object value in select
- Making an array bindable in a function component
- React: How to run a background animation with onClick?
- GitHub Pages Page Not Found for React App
- What does "CI=false npm run build" mean to not treat warnings as errors on Netlify or Vercel?
- React Redux filter actions (generic sorting example)
- How do I make my React file sleep for 5 seconds before continuing?
- Why browser is not setting the cookie sent from my node js backend?
- Is it a good practice to create base components and then extend them in React?
- How to link or route the react semantic UI dropdown component
- How do I prevent drop in originating container in react js and react-beautiful-dnd?
- How to remove bad objects from my reponse.data before setting state
- How to exclude mobx and mobx-react from the bundle using webpack
- How to create custom CSS classes using MUI v5 theme?
- How to change the internal state property of a component in an action creator function