Sunday, July 18, 2021

React CheckBox

Working with React Bootstrap checkbox


 import React, { PureComponent } from "react";
import Form from "react-bootstrap/Form";

interface CheckBoxState {
  checkedColors: any[];
}

interface CheckBoxProps {
  foo: string;
}

class CheckBox extends PureComponent<CheckBoxProps, CheckBoxState> {
  constructor(props: CheckBoxProps) {
    super(props);
    this.state = {
      checkedColors: [
        { isChecked: false, name: "chk1", label: "blue" },
        { isChecked: false, name: "chk2", label: "red" },
      ],
    };
  }

  render() {
    return (
      <div>
        {this.state.checkedColors.map((item: any) => (
          <Form.Check
            type="checkbox"
            id={item.name}
            inline
            key={item.name}
            checked={item.isChecked}
            onChange={(event: any) => this.handleChange(event)}
            label={item.label}
          />
        ))}
        <button onClick={() => console.log(this.state.checkedColors)}>
          Show checked colors
        </button>

        <hr />
        {this.props.foo}
      </div>
    );
  }

  handleChange(event: any): void {
    const checkedColors = [...this.state.checkedColors];

    checkedColors.map((item: any) => {
      if (item.name === event.target.id) item.isChecked = event.target.checked;
    });

    this.setState({
      checkedColors,
    });
  }
}

export default CheckBox;
Note that this.state.checkedColors can be cloned using spread operator 'cause the array is shallow.