Skip to content

JSX

Rendering a List

tsx
import { Fragment } from "react";

function Comp() {
  const items = [
    { id: 1, name: "Item 1" },
    { id: 2, name: "Item 2" },
    { id: 3, name: "Item 3" },
  ];

  return (
    <div>
      {items.map((item) => {
        return <Fragment key={item.id}>{item.name}</Fragment>;
      })}
    </div>
  );
}

Conditional Rendering

tsx
function Comp() {
  const items = [
    { id: 1, name: "Item 1", show: true },
    { id: 2, name: "Item 2", show: true },
    { id: 3, name: "Item 3", show: false },
  ];

  return (
    <div>
      {items.map((item) => {
        return {item.show && <Fragment key={item.id}>{item.name}</Fragment>};
      })}
    </div>
  );
}

Checking if item is valid

tsx
function Comp() {
  const items: object[] | null = null;

  return <div>{items?.length || "No items"}</div>;
}

Two-way data binding

In order to have two-way data binding between the component and an input or another child component, you need to make use of the onChange event or some other event callback.

tsx
import { useState } from "react";

function Comp() {
  const [value, setValue] = useState("");

  return <input value={value} onChange={(e) => setValue(e.target.value)} />;
}

Handling number inputs

tsx
import { useState } from "react";

function Comp() {
  const [value, setValue] = useState(0);

  const handleChange = (e) => {
    // will be NaN if invalid input or empty
    newValue = parseInt(e.target.value) || 0;
    // do something with new value
  };

  // need || "" or else it will always have an annoying 0 in the input
  return <input type="number" value={value || ""} onChange={handleChange} />;
}