Deactivate input in react with a button click

Second Son picture Second Son · Apr 21, 2016 · Viewed 57.8k times · Source

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>
          );
};

Answer

wintvelt picture wintvelt · Apr 21, 2016

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.