1

This checkbox is permanently checked, I want the pre selected checkbox to change the boolean state. I'm currently using this handleChange method to deal with text inputs. Do I have to create another method to deal with the checkbox or can I add to the existing method?

state = {
  billingEmail:'',
  billingAddressSame: true,
}
handleChange = input => e => {
   this.setState({[input]: e.target.value})
}
<input
  className="col-sm-12"
  type="email"
  placeholder="Email"
  onChange={handleChange('billingEmail')}
  defaultValue={values.billingEmail}
/>

<label className="col-sm-12" style={{paddingLeft: "0"}}>
  <input
    type="checkbox"
    checked={values.billingAddressSame}
    onChange={handleChange('billingAddressSame')}
  />
  Same as company address
</label>
drewgorms
  • 23
  • 1
  • 4

3 Answers3

0

Change your handleChange function to

handleChange = input => e => {
   this.setState({[input]: !this.state[input]})
}
Burak Gavas
  • 1,304
  • 1
  • 9
  • 11
  • This changes all of my states to a boolean. I still need to store strings in other states. This could work if I used 2 different methods. – drewgorms Mar 09 '20 at 13:29
0

You can control your checkbox and input by a single method.

See

Constructor and handle change function-

constructor(props) {
 super(props);
 this.state = {
  isGoing: true,
  numberOfGuests: 2
 };

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

handleInputChange(event) {
 const target = event.target;
 const value = target.type === 'checkbox' ? target.checked : target.value;
 const name = target.name;

 this.setState({
   [name]: value
 });
}

And in your render function -

render() {
 return (
  <form>
    <label>
      Is going:
      <input
        name="isGoing"
        type="checkbox"
        checked={this.state.isGoing}
        onChange={this.handleInputChange} />
    </label>
    <label>
      Number of guests:
      <input
        name="numberOfGuests"
        type="number"
        value={this.state.numberOfGuests}
        onChange={this.handleInputChange} />
    </label>
  </form>
 );
}

See this for more info

Alok Mali
  • 2,821
  • 2
  • 16
  • 32
0

try this and let me know, its working fine for me

import React, { Component, Fragment } from 'react';

class SignUp extends Component{
  state = {
    billingEmail:'',
    billingAddressSame: true,
  }

  render(){
    return(<Fragment>

      <input className="input" type="email" className="col-sm-12" placeholder="Email" value={this.state.billingEmail} onChange={e => this.setState({billingEmail: e.target.value})}/>

      <label className="col-sm-12" style={{paddingLeft: "0"}}>
      <input type="checkbox" value="CheckBox1" checked={this.state.billingAddressSame} onChange={e => this.setState({ billingAddressSame: !this.state.billingAddressSame })} />
        Same as company address
      </label>
    </Fragment>)
  }
}

export default SignUp;
John Clinton
  • 204
  • 1
  • 6