@aminnairi/preact-switch
v1.0.0
Published
Preact component for conditional rendering
Downloads
8
Maintainers
Readme
@aminnairi/preact-switch
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
.