Like (let)
in Lisp, Clojure, etc., but for React/JSX.
Makes it easier to declare variables deep inside a JSX tree,
which are then passed to a children
render function.
When used with TypeScript, the render function arguments are infered from the props given to <Let>
.
npm add react-let
# alternative:
yarn add react-let
import React from "react";
import { Let } from "../main";
export const ExampleMemo = () => (
<div>
<Let result={"expensive-calculation-result"} another={42}>
{({ result, another }) => ( // TypeScript infered: (parameter) result: string; (parameter) another: number
<p>
{result}. {another}.
</p>
)}
</Let>
</div>
);
export const ExampleInput = () => (
<div>
<Let id={"myId"}>
{({ id }) => ( // TypeScript infered: (parameter) id: string
<>
<label htmlFor={id}>{id}</label>
<input id={id} />
</>
)}
</Let>
</div>
);
export const ExampleAsync = () => {
type FetchData = { str: string; num: number };
type FetchResult = { state: "loading" | "finished" | "error"; data?: FetchData };
const [fetchResult, setFetchResult] = useState<FetchResult>({ state: "loading" });
return (
<div>
{fetchResult.state === "loading" ? (
"loading…"
) : fetchResult.state === "error" ? (
"error!"
) : (
<Let data={fetchResult.data}>
{({ data }) => ( // TypeScript infered: (parameter) data: FetchData
<>
<pre>{JSON.stringify(data)}</pre>
</>
)}
</Let>
)}
</div>
);
};
All examples can be found in src/example/App.tsx
,
and be can be run using:
npm ci
npm run dev
Instead of using this component, you can use an IIFE inside which you can declare JavaScript variables normally (i.e. you can use statements and not just expressions).
export const ExampleVanilla = () => (
<div>
{(() => {
const result = "expensive-calculation-result";
const another = 42;
return (
<p>
{result}. {another}.
</p>
);
})()}
</div>
);
The command to run the examples could is used for development (but no work is currently planned as the component is feature-complete).
To publish a new version:
npm version <major|minor|patch|…>
npm publish && \
git push --tags origin HEAD:main
© Max F. Albrecht https://github.com/eins78
License: MIT https://eins78.mit-license.org