Light box with suspense
The items will take a random time between 0 and 3 seconds before they "load".
import { useState } from 'react';
import { LightBox } from '@citizensadvice/react-dialogs';
const loaded = new Set();
function useDataLoader(title) {
if (loaded.has(title)) {
return;
}
// React suspense works by catching a thrown promise
// Then re-rendering the component when it resolves
throw new Promise((resolve) => {
setTimeout(() => {
loaded.add(title);
resolve();
}, Math.random() * 3e3);
});
}
function Item({ title, children }) {
useDataLoader(title);
return children;
}
export function Example() {
const [show, setShow] = useState();
const [index, setIndex] = useState(0);
return (
<>
<button
type="button"
onClick={() => setShow(!show)}
aria-expanded={show}
aria-haspopup="dialog"
>
Toggle
</button>
{show && (
<LightBox
onClose={() => setShow(false)}
onChangeIndex={setIndex}
index={index}
>
<Item title="Item 1">
<p>
1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</Item>
<Item title="Item 2">
<p>
2. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</Item>
<Item title="Item 3">
<p>
3. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</Item>
<Item title="Item 4">
<p>
4. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</Item>
<Item title="Item 5">
<p>
5. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</Item>
</LightBox>
)}
</>
);
}