S
S
Sss1092021-10-10 16:55:07
React
Sss109, 2021-10-10 16:55:07

How can I change the state of the checkbox when changing the select?

Given a select with two values: 'checked' and 'unchecked'. There is also a checkbox. It is necessary to make sure that when the value of the select changes, the checkbox changes its state from 'checked' to 'unchecked' and vice versa.
There are no problems with the creation, I do not understand how to connect them.

constructor() {
    	super();
        this.state = {checked: true};
    	this.state = {
    		value: 0,
    		sost: [
    			'Отмечено',
    			'Не отмечено',
    			]
    		};
    	}
        handleSelectChange(event) {
        	this.setState({value: event.target.value});
        	}
  handleCheckboxChange(event) {
    this.setState({checked: !this.state.checked});
  }
  render() {
                const options = this.state.sost.map((item, index) => {
      	         return <option key={index} value={index}>{item}</option>;
      		});
    return <div>
      <select
        value={this.state.value}
        onChange={this.handleSelectChange.bind(this)}
      >
        {options}
  </select>
      <p>Состояние: {this.state.sost[this.state.value] ? 'Отмечено' : 'Не отмечено'}</p>
      <input
        type="checkbox"
        checked={this.state.sost}
        onChange={this.handleSelectChange.bind(this)}
      />
    </div>;
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-10-10
@Sss109

state = {
  value: 0,
  options: [ 'Не отмечено', 'Отмечено' ],
}

onChange = ({ target: t }) => {
  this.setState(() => ({
    value: +t[t.dataset.stateAttr],
  }));
}

render() {
  const { value, options } = this.state;

  return (
    <div>
      <select
        value={value}
        onChange={this.onChange}
        data-state-attr="value"
      >
        {options.map((n, i) => <option value={i}>{n}</option>)}
      </select>
      <br />
      <label>
        <input
          type="checkbox"
          checked={value}
          onChange={this.onChange}
          data-state-attr="checked"
        />
        {options[value]}
      </label>
    </div>
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question