I have this basic component and I want the textfield to be deactivated or activated whenever I click on a button. How can I achieve this?
This is my sample code:
import React from "react"; import Button from 'react-button' const Typing = (props) => { var disabled = "disabled"; var enabled = !disabled; const handleUserInput = (event) => props.onUserInput(event.target.value); const handleGameClik = (props) => { disabled = enabled; } return( <div> <input className = "typing-container" value = {props.currentInput} onChange = {handleUserInput} placeholder=" ^__^ " disabled = {disabled}/> <Button onClick = {handleGameClik}> Start Game </Button> <Button> Fetch Data </Button> </div> ); };
Disable the TextBox by adding the e-disabled to the input parent element and set disabled attribute to the input element.
To clear an input field with React, we can set the value of the value attribute to an empty string. We create the val state with the useState hook. Then we set the value prop of the input to the val state. Next we set the onClick prop of the button to a function that calls setVal to an empty string.
To prevent multiple button clicks in React: Set an onClick prop on the button, passing it a function. When the button gets clicked, set its disabled attribute to true .
To disable a button when an input is empty with React, we can set the input's value as a state's value. Then we can use the state to conditionally disable the button when the state's value is empty. to create the name state with the useState hook.
A simplified solution using state could look like this:
class Typing extends React.Component { constructor(props) { super(props); this.state = { disabled: false } } handleGameClik() { this.setState( {disabled: !this.state.disabled} ) } render() { return( <div> <input className = "typing-container" placeholder= " type here " disabled = {(this.state.disabled)? "disabled" : ""}/> <button onClick = {this.handleGameClik.bind(this)}> Start Game </button> <button> Fetch Data </button> </div> ); } };
Working Codepen here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With