Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deactivate input in react with a button click

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>           ); }; 
like image 318
Second Son Avatar asked Apr 21 '16 15:04

Second Son


People also ask

How do you disable an input in React?

Disable the TextBox by adding the e-disabled to the input parent element and set disabled attribute to the input element.

How remove input field from button click in react JS?

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.

How do I restrict button click in React?

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 .

How do you disable a button when input is empty in React?

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.


1 Answers

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.

like image 94
wintvelt Avatar answered Sep 20 '22 18:09

wintvelt