stephencurry30
stephencurry30

Reputation: 127

React - checkbox does not toggle

I am able to successfully change the discount amount from 0 to 50% off when the user checks the box off but it does not toggle off afterwards.

I'm assuming something is wrong with the handleChange function:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    // Define data above render()
    constructor(){
      super(); 

      this.state = {
        discount: 0,
      }

      this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {

         this.setState({
            discount: event.target.checked = this.state.discount = .50});
    } 

    render() {

        return( 
            <div>
            Apply 50% discount:
            <input type='checkbox' value={this.state.discount} checked={this.state.discount} checked={this.state.discount} onChange={this.handleChange} />
            <br/><br/>);     
    }
}

export default App;

Upvotes: 1

Views: 1538

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30370

It looks like you're missing an = in your handleChange function, which is causing the state update to behave incorrectly.

Try revising this function like so, for clarity and correctness:

handleChange(event) {

  // Toggle the discount value between 0.5 and 0.0 via this logic
  const nextDiscount = (this.state.discount === 0.5) ? 0.0 : 0.5

  // Update discount state with nextDiscount value
  this.setState({ discount: nextDiscount });
} 

Also, consider updating your render() method so that the value for the checked prop evaluates to truthy/falsey based on the value of this.state.discount (ie via this expression (this.state.discount === 0.5)). Also ensure that only one checked prop is passed to that checkbox input:

render() {

    return(<div>
        Apply 50% discount:
        <input type='checkbox' 
               value={this.state.discount} 
               checked={ (this.state.discount === 0.5) } 
               onChange={this.handleChange} />
        <br/>
        <br/>);     
}

Upvotes: 1

Related Questions