Sandpack is a lightweight code playground built by the CodeSandbox team.
With Sandpack, you can compose built-in and custom React components to create unique experiences for your end users.
In this post, we're going to focus on the built-in SandpackPreview
component.
The Sandpack Preview Component
The Preview component is your window into Sandpack's bundling process. It shows you how your UI looks. Not only that, but it also supports live updates when you make changes in an Editor component:
How to support browser navigation.
Just like a regular browser, the Preview component has a search bar. You can enable it with the showNavigator
prop. You don't need to use the search bar, but it can be useful when building a demo that involves routing:
In the example above, we're using React Router. We've defined a root route at /
and another route at /secret
. By default, the app is on the /
route which shows a page with the text "Hello world!".
Try using the search bar to navigate to the /secret
route. The page should update and show the text "Hello Secret!" now!
Great! But what if we want the app to start on the /secret
route instead of the /
route?
Well, that's easy too!
You can use the startRoute
prop like below:
You can add custom actions to your Preview component.
The Preview component supports custom actions. The idea is that you can use a custom action to provide additional functionality to your playground. Let's say I wanted a way to toggle the search bar in the previous example.
We can combine React state with a basic toggle button to accomplish this:
You can use refs to interact with the Sandpack client.
Let's say I'm building a demo to showcase Tailwind CSS.
I want to include a button to add or remove Tailwind from the page. This will make it easier to compare the UI with and without Tailwind. An easy way to add Tailwind to a Sandpack instance is to pass the CDN to Sandpack as an external resource.
But how do you update the external resources?
We can't do this with just a custom action. Instead, we can pass a React ref to the Preview component. The Preview component uses React's useImperativeHandle hook to attach a handler function that returns the underlying Sandpack client to the ref.
We can use the Sandpack client to update the external resources and refresh the Preview:
This pattern is useful because it automatically refreshes the Preview with the new resource.
In fact, this is a pattern I follow in Kempo:
And that's it!
Hopefully, this helps you use Sandpack's Preview component more effectively!