Enable or disable a button based on a TextField value in React.js
The problem here is that setState
is async and you are using state values inside handleOnChange
before it is updated. Either use setState callback to calculate disable
or a better way is to calc disabled
in render. This approach makes it much simpler and even works while rendering for the first time.
render() {
const disabled = !this.state.company_tag.length;
return (
// ...
<Button
disabled={disabled}
onClick={this.handleOnSelect}
variant="raised"
color="secondary"
>
Add
</Button>
// ...
);
}
Check the example below using React Hooks for the button state, and the onChange property of the TextField to set it.
export default function TextFieldAndButton (props) {
const [btnDisabled, setBtnDisabled] = useState(true)
return (
<>
<TextField
onChange={(text) => setBtnDisabled(!text.target.value)}
/>
<Button disabled={btnDisabled}>OK</Button>
</>
)
}