Showing posts with label TypeScript. Show all posts
Showing posts with label TypeScript. Show all posts

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.

Thursday, April 15, 2021

TypeScript Question Mark and Exclamation Mark

Here is how to use in combination to determine if property is null or undefined.

interface Product {
    id: number,
    name?: any 
}

let product: Product = {id: 5, name: "some str"};

if(product!.name) console.log("ok")

product = {id: 5}
if(product!.name) console.log("not printed")

product = {id: 5, name: null}
if(product!.name) console.log("not printed")

Second if will not be excecated 'cause property name is not defined. Third if will not be execute 'cause property name is null.