@aminnairi/preact-switch

1.0.0 • Public • Published

@aminnairi/preact-switch

NPM version Coverage Status Number of vulnerabilities Size of the NPM package Tree shaking support

Requirements

  • Node.js
  • NPM

Installation

$ npm install @aminnairi/preact-switch

Features

  • Conditional rendering directly in JSX.
  • No more messy brackets, ternary and short-circuit evaluation in JSX.
  • Just like a switch in JavaScript.
  • Strict runtime checking.
  • No switch without case or default.
  • No case nor default without children.
  • Error thrown when used incorrectly and recoverable with useErrorBoundary.

Usage

Basic

import {h} from "preact";
import {Switch, Case, Default} from "@aminnairi/preact-switch";

const App = () => (
  <Switch target="ok">
    <Case condition={target => target === "great"}>
      Glad you are doing great!
    </Case>
    <Case condition={target => target === "ok"}>
      I hope that everything is okay!
    </Case>
    <Case condition={target => target === "bad"}>
      Is there anything I can do for you?
    </Case>
    <Default>
      Have a great one!
    </Default>
  </Switch>
);

export default App;

Advanced

import {h, Fragment} from "preact";
import {useState, useCallback, useErrorBoundary} from "preact/hooks";
import {Switch, Case, Default} from "@aminnairi/preact-switch";

const App = () => {
  const [error] = useErrorBoundary();

  const [mood, setMood] = useState("ok");
  const updateMood      = useCallback(({target: {value}}) => setMood(value), []);
  
  const isGreatMood = useCallback(target => target === "great", []);
  const isOkMood    = useCallback(target => target === "ok", []);
  const isBadMood   = useCallback(target => target === "bad", []);
  
  if (error) {
    return (
      <Fragment>
        <h2>Error</h2>
        <p>An error occurred</p>
        <small>Reason: {error.message}</small>
      </Fragment>
    );
  }

  return (
    <Fragment>
      <select value={mood} onChange={updateMood}>
        <option value="great">Great</option>
        <option value="ok">Ok</option>
        <option value="bad">Bad</option>
      </select>
      <Switch target={mood}>
        <Case condition={isGreatMood}>
          Glad you are doing great!
        </Case>
        <Case condition={isOkMood}>
          I hope that everything is okay!
        </Case>
        <Case condition={isBadMood}>
          Is there anything I can do for you?
        </Case>
        <Default>
          Have a great one!
        </Default>
      </Switch>
    </Fragment>
  );
};

export default App;

See examples.

Contributing

See CONTRIBUTING.md.

License

See LICENSE.

Changelog

See CHANGELOG.md.

Package Sidebar

Install

npm i @aminnairi/preact-switch

Weekly Downloads

2

Version

1.0.0

License

GPL-3.0-or-later

Unpacked Size

45.8 kB

Total Files

7

Last publish

Collaborators

  • aminnairi