`re-tk` is a collection of lodash-style React helpers (mostly hooks) to make everyday code quicker to write and easier to read.
npm install re-tkre-tk is a collection of lodash-style React helpers (mostly hooks) to make everyday code quicker to write and easier to read.
It can help with common tasks like...
- data fetching and other async tasks ⏳
- running media queries 🖥
- checking if an element is in view 🔎
... and many more!
Detect wether an element is in view using the IntersectionObserver API.
Pass in a boolean as a default value (false is used if none is provided), and, optionally, any extra options for the created IntersectionObserver (see here).
Returns a ref which should be passed as the ref prop to the element you want to observe, and a boolean to represent wether or not the element is in view
``jsx
import { useInView } from 're-tk'
const boxStyle = {
height: "400px",
width: "500px",
border: "1px solid black",
display: "inline-block",
};
const labelStyle = {
position: "fixed",
top: 0,
left: 0,
background: "blue",
color: "white",
};
const InViewReporter = () => {
const [ref, inView] = useInView(false);
return (
<>
}`
Return true if the media query matches, or false if the query does not match
`jsx
import { useMediaMatch } from 're-tk'
const SmallScreenDetector = () => {
const isSmallScreen = useMediaMatch("(max-width: 375px)");
if (isSmallScreen) {
return
return
`
Run an async function (anything returning a Promise) and return the resolved value, error if any (defaults of null for both), and a rerun function to trigger the function to run again
`jsx
import { usePromise } from 're-tk'
const fetchTodo = () =>
fetch("https://jsonplaceholder.typicode.com/todos/1").then((res) =>
res.json()
);
const FetchingData = () => {
const [data, error, rerun] = usePromise(fetchTodo);
return (
The data is: {JSON.stringify(data, null, 2)}
The error is: {error}
);
};
`
`jsx
import { usePromise } from 're-tk'
const failingFetch = () => Promise.reject("Something went wrong!");
const PromiseRejected = () => {
const [data, error] = usePromise(failingFetch);
return (
The data is: {data}
The error is: {error ? error.message : null}
);
};
`
Simple useState-style hook for a boolean toggle, great for closable popups and checkboxes.
`jsx
import { useToggle } from 're-tk'
const DescribedCheckbox = () => {
const [isToggled, toggle] = useToggle(false);
return (
<>
type="checkbox"
checked={isToggled}
onChange={() => toggle()}
/>
``