Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set checkbox value in React JS

I'm trying to change the value of the checkbox with the onChange function of another input field.

I have something like this:

class price extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            minValue: 0,
            maxValue: 20000,
            step: 1000,
            firstValue: null,
            secondValue: null,
            chcboxValue: false
        };

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

    componentWillMount() {
        this.setState({firstValue: this.state.minValue, secondValue: this.state.maxValue});
    }

    handleChange(name, event) {
        let value = event.target.value;
        // We set the state value depending on input that is clicked
        if(name === "second") {
            if(parseInt(this.state.firstValue) < parseInt(value)) {
                this.setState({secondValue:value});
            }
        } else {
            // The first value can't be greater than the second value
            if(parseInt(value) < parseInt(this.state.secondValue)) {
                this.setState({firstValue: value});
            }
        }

        // We set the checkbox value
        if(parseInt(this.state.firstValue) != parseInt(this.state.minValue) || parseInt(this.state.secondValue) != parseInt(this.state.maxValue)) {
            this.setState({chcboxValue: true});
        } else {
            this.setState({chcboxValue: false});
        }
    }

    render() {
        const language = this.props.language;
        return (
            <div>
                <div className="priceTitle">{language.price}</div>
                <InputRange language={language}
                            firstValue={parseInt(this.state.firstValue)}
                            secondValue={parseInt(this.state.secondValue)}
                            minValue={parseInt(this.state.minValue)}
                            maxValue={parseInt(this.state.maxValue)}
                            step={parseInt(this.state.step)}
                            handleChange={this.handleChange}
                            chcboxValue={this.state.chcboxValue}/>
            </div>
        );
    }
}

My InputRange component is something like this:

const inputRange = ({language, firstValue, secondValue, minValue, maxValue, step, handleChange, chcboxValue}) => {
    return (
        <div>
            <div className="rangeValues">Range : {firstValue} - {secondValue}</div>
            <section className="range-slider">
                <input type="checkbox" checked={chcboxValue} />
                <input type="range" value={firstValue} min={minValue} max={maxValue} step={step}  onChange={handleChange.bind(this, "first")} />
                <input type="range" value={secondValue} min={minValue} max={maxValue} step={step} onChange={handleChange.bind(this, "second")} />
                <div className="minValue">{minValue}</div>
                <div className="maxValue">{maxValue}</div>
            </section>
        </div>
    );
};

The checkbox value on initial load is set to false. When the user changes the value of the price range slider, I want that the checkbox value to change to true.

When the user changes the value of the price range slider to their initial values (min and max values), I want the checkbox value to again change to false.

It isn't working in my example.

Any ideas?

like image 278
Boky Avatar asked Aug 30 '16 09:08

Boky


People also ask

How do you change the value of checkbox in React?

Use the defaultChecked prop to set the default checked value of a checkbox in React, e.g. defaultChecked={true} . Input elements with type set to checkbox support the defaultChecked prop for setting a default value.

How check if checkbox is reacted?

Use the target. checked property on the event object to check if a checkbox is checked in React, e.g. if (event. target. checked) {} .

How do you handle a checkbox in React?

In React, the best way to do this is via the useState hook. This is different from normal JavaScript because we are unable to access the value of the checkbox directly from its DOM component: /* Create a checkbox functional component. Toggle the text of a paragraph with the checkbox using the 'useState' hook.

How to create a checkbox in react app?

In the first step we set the initial state of fruits options. Define React onChange event in HTML checkbox element and set the checkbox value in it. When updated by user, this method will update the checkbox’s state. Go to src/App.js file and add the following code for checkboxes demo:

How to update checkbox’s state in react onchange?

Keep all the below logic in src/App.js file: In the first step we set the initial state of fruits options. Define React onChange event in HTML checkbox element and set the checkbox value in it. When updated by user, this method will update the checkbox’s state.

What are react checkboxes onchange event handlers?

However, modern websites often benefit from a more seamless experience. Checkboxes are an example of an element that would traditionally be included as part of a form. In this tutorial, we’ll learn how to utilize React Checkboxes onChange event handler to call functions without explicitly pressing submit.

How do I declare an array of checkboxes in a state?

So let's declare an array in the state indicating the state of each checkbox. To create an array equal to the length of the number of checkboxes, we can use the array fill method like this: Here, we've declared a state with an initial value as an array filled with the value false.


3 Answers

not sure but try it :

React.createElement('input',{type: 'checkbox', defaultChecked: false});

or

<input type="checkbox" checked={this.state.chkbox} onChange={this.handleChangeChk} />

or

var Checkbox = React.createClass({
  getInitialState: function() {
    return {
      isChecked: true
    };
  },
  toggleChange: function() {
    this.setState({
      isChecked: !this.state.isChecked // flip boolean value
    }, function() {
      console.log(this.state);
    }.bind(this));
  },
  render: function() {
    return (
      <label>
        <input
          type="checkbox"
          checked={this.state.isChecked}
          onChange={this.toggleChange} />
        Check Me!
      </label>
    );
  }
});

React.render(<Checkbox />, document.getElementById('checkbox'));
like image 90
Neeraj Prajapati Avatar answered Oct 01 '22 09:10

Neeraj Prajapati


Your example is not working properly because you are checking the value before this.setState() is completed. Don't forget that this.setState() does not immediately mutate the state.

To fix it, you can create a function where you update the value of the checkbox

updateCheckBox(){
   if(parseInt(this.state.firstValue) != parseInt(this.state.minValue) || parseInt(this.state.secondValue) != parseInt(this.state.maxValue)){
        this.setState({chcboxValue: true});
    }else{
        this.setState({chcboxValue: false});
    }
}

and then pass it to your handleChange this.setState() calls.

handleChange(name, event){
    let value = event.target.value;
    //We set the state value depending on input that is clicked
    if(name === "second"){
        if(parseInt(this.state.firstValue) < parseInt(value)){
            this.setState({secondValue:value}, this.updateCheckBox);
        }
    }else{
        //The first value can't be greater than the second value
        if(parseInt(value) < parseInt(this.state.secondValue)) {
            this.setState({firstValue: value}, this.updateCheckBox);
        }
  }

jsfiddle

like image 20
QoP Avatar answered Oct 01 '22 10:10

QoP


This is kind of old but in case it helps.

I started relying on this syntax

Declare in the class, a variable to store the state:

const [agreeToAllTerms, setAgreeToAllTerms] = useState(false);

Declare the checkbox

<Checkbox checked={agreeToAllTerms} onChange={(event)=> {handleChangeChk(event)}}/> 

And then in the function checked the current state of the checkbox like this.

const handleChangeChk = (chkValue) => {
    setAgreeToAllTerms(chkValue.target.checked);
}
like image 35
KManish Avatar answered Oct 01 '22 09:10

KManish