How to enable live running code IDE in the website with Codesandbox?
How to enable live running code IDE in the website with Codesandbox?

Nextjs

How to enable live running code IDE in the website with Codesandbox?

Enabling live code in the browser using Sandpack.

--

The best way to learn a programming language or library is through documentation.

Many documentation websites, such as reactjs docs, have recently used an interaction live code IDE for their examples.

Live running code IDE example built with Sandpack.
Live running code IDE example built with Sandpack

It helps to improve the learning speed, and the developer quickly understands the concept by interacting with live code inside IDE.

Similarly, you can use live code IDE for tutorials or documentation. You can very easily add it to your website using the Sandpack library.

The sandpack is a library built by codesandbox. The codesandbox is an instant cloud development environment.

All the code is available on github.

In this tutorial, we understand how you can enable live code IDE for tutorials or documentation websites by following the below steps.

  1. Create a fresh app
  2. Install the sandpack package.
  3. Uses of the sandpack package.
    · configurations
    Templates
    Files
    Theme
    Dependencies
    Read-only mode
    visibleFiles and activeFile
    Custom Entry File
    · Options
    Layout mode
    Navigator
    Editor Settings

Create a fresh app

The first step is to create a fresh new nextjs application using the create next app. If you already have a project, then skip this section.

➜  medium pnpm create next-app@latest codesandbox-ide                            
.../share/pnpm/store/v3/tmp/dlx-73449 | +1 +
.../share/pnpm/store/v3/tmp/dlx-73449 | Progress: resolved 1, reused 1, downloaded 0, added 1, done
✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like to use `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to customize the default import alias (@/*)? … No / Yes
✔ What import alias would you like configured? … @/*
Creating a new Next.js app in /home/officialrajdeepsingh/medium/codesandbox-ide.

Using pnpm.

Initializing project with template: app-tw


Installing dependencies:
- react
- react-dom
- next

Installing devDependencies:
- typescript
- @types/node
- @types/react
- @types/react-dom
- postcss
- tailwindcss
- eslint
- eslint-config-next

Packages: +349
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Progress: resolved 357, reused 344, downloaded 5, added 349, done

dependencies:
+ next 14.2.3
+ react 18.3.1
+ react-dom 18.3.1

devDependencies:
+ @types/node 20.12.12
+ @types/react 18.3.2
+ @types/react-dom 18.3.0
+ eslint 8.57.0 (9.3.0 is available)
+ eslint-config-next 14.2.3
+ postcss 8.4.38
+ tailwindcss 3.4.3
+ typescript 5.4.5

Done in 5m 43.3s
Initialized a git repository.

Success! Created codesandbox-ide at /home/officialrajdeepsingh/medium/codesandbox-ide

Install the sandpack package.

The next step is to install the sandpack library in your project using the node package manager. I choose pnpm as the node package manager.

➜  codesandbox-ide git:(main) ✗ pnpm add @codesandbox/sandpack-react                                   
Packages: +49
+++++++++++++++++++++++++++++++++++++++++++++++++
Downloading registry.npmjs.org/@codesandbox/sandpack-client/2.13.8: 17.59 MB/17.59 MB, done
Progress: resolved 406, reused 365, downloaded 33, added 49, done
node_modules/.pnpm/es5-ext@0.10.64/node_modules/es5-ext: Running postinstall script, done in 83ms

dependencies:
+ @codesandbox/sandpack-react 2.13.10

Done in 1m 56.1s

Uses of the sandpack package.

You can easily use the sandbox library in your React and nextjs applications.

Copy and paste the following code example into the app/page.tsx file.

// app/page.tsx

"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
theme="light"
template="react"
files={{
"/App.js": `export default function app() {

return (<p>Hello, World!</p>)

}`
}}
/>
)
}

After opening your local development host on the browser, your IDE looks like this.

Sandpack basic IDE example.
Sandpack basic IDE example.

configurations and options

There are lots of configurations and options that come with sandpack. You can easily enable it.

In this tutorial, we will learn some standard configurations and options. For others, you can follow the sandpack documentation.

configurations

  1. Templates (compulsory)
  2. Files (compulsory)
  3. Theme
  4. Dependencies
  5. Read-only mode
  6. Custom Entry File

Templates

By default, Sandpack comes with a predefined template, such as Static, Angular, React, Solid, Svelte, Vanilla, Vue, Node, Nextjs, Vite, React (Vite), Preact (Vite), Vue (Vite), Svelte (Vite) and Astro. With predefined templates, start the work faster.

<Sandpack template="react" />
# or
<Sandpack template="nextjs" />
# or
<Sandpack template="angular" />

Files

After selecting the starter template, the next step is to pass custom code into your Sandpack instance. You can pass your code as props with files.

"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
template="react"
files={{
"/App.js": `export default function App() {
return <h1>Hello world</h1>
}`,
}}
/>
)}

You can define not only one file but also add multiple files. You can import components from other files.

"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
template="react"
files={{

"/App.js": `import { Hero } from "./Hero"; \n
export default function app() {

return <Hero />

}`,

"/Hero.js":`export function Hero() {

return (
<div class="card">
<h1>Hello World</h1>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p>
<a title="read more"> Read more about the offer » </a>
</div>
)}`

}}
/>
)}

Theme

Sandpack has come with more than 19 themes. Sandpack offers a set of predefined dark and light themes.

<Sandpack theme="auto" /> // System color scheme (light or dark)

<Sandpack theme="light" /> // light theme

<Sandpack theme="dark" /> // dark theme

For others, themes come from @codesandbox/sandpack-themes; it is an open-source package that contains many other themes compatible with Sandpack.

First install the @codesandbox/sandpack-themes package with npm, yarn or pnpm. After that, you can easily use it.

import { amethyst } from "@codesandbox/sandpack-themes"; // Install it with npm, yarn and pnpm.    

<Sandpack theme={amethyst} />; // uses it.

Your theme look like this.

Theme

Dependencies

The template property only includes needed dependencies. In addition, You can also specify additional dependencies using customSetup property.

  1. NPM Dependencies
  2. Static External Resources

NPM Dependencies

Install additional dependencies from npm registry, which are required to run your IDE in the browser.

"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
customSetup={{
dependencies: {
"title": "latest"
}
}}
template="react"
files={{
"/App.js": `import { Hero } from "./Hero"; \n
export default function app() {

return <Hero />

}`,
"/Hero.js": `import title from 'title';

export function Hero() {

return (
<div class="card">
<h1>{title('Hello world')}</h1>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p>
<a href="#" title="read more"> Read more about the offer » </a>
</div>
)}`
}}
/>
)
}

Otherwise, you can face error.

Otherwise your face error.
Otherwise your face error.

Static External Resources

To add other external resources into the options props to specify static links to external CSS or JS resources elsewhere on the web.

The external resources are injected into the head of your HTML and are then globally available.

To add external resources, you can use the options property, and inside options, you can define the externalResourcesproperty. The externalResources property contains an array of strings.

"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
options={{
externalResources: ["https://cdn.tailwindcss.com"] // add external resources with CDN.
}}

...
/>
)}

For first example, an example using the Tailwind CSS with CDN:

"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
template="react"
options={{
externalResources: ["https://cdn.tailwindcss.com"]
}}
files={{
"/App.js": `export default function Example() {
return (
<div className="bg-gray-50">
<div className="mx-auto max-w-7xl py-12 px-4 sm:px-6 lg:flex lg:items-center lg:justify-between lg:py-16 lg:px-8">
<h2 className="text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">
<span className="block">Ready to dive in?</span>
<span className="block text-indigo-600">Start your free trial today.</span>
</h2>
<div className="mt-8 flex lg:mt-0 lg:flex-shrink-0">
<div className="inline-flex rounded-md shadow">
<a
href="#"
className="inline-flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-5 py-3 text-base font-medium text-white hover:bg-indigo-700"
>
Get started
</a>
</div>
<div className="ml-3 inline-flex rounded-md shadow">
<a
href="#"
className="inline-flex items-center justify-center rounded-md border border-transparent bg-white px-5 py-3 text-base font-medium text-indigo-600 hover:bg-indigo-50"
>
Learn more
</a>
</div>
</div>
</div>
</div>
)
}`
}}
/>
)}

For second example you can use jQuery and bootstrap with CDN:

"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
template="react"
options={{
externalResources: ["https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css", "https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"]
}}
files={{
"/App.js": `export default function Example() {
return (
<div className="bg-gray-50">
<div className="mx-auto max-w-7xl py-12 px-4 sm:px-6 lg:flex lg:items-center lg:justify-between lg:py-16 lg:px-8">
<h2 className="text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">
<span className="block">Ready to dive in?</span>
<span className="block text-indigo-600">Start your free trial today.</span>
</h2>
<div className="mt-8 flex lg:mt-0 lg:flex-shrink-0">
<div className="inline-flex rounded-md shadow">
<a
href="#"
className="inline-flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-5 py-3 text-base font-medium text-white hover:bg-indigo-700"
>
Get started
</a>
</div>
<div className="ml-3 inline-flex rounded-md shadow">
<a
href="#"
className="inline-flex items-center justify-center rounded-md border border-transparent bg-white px-5 py-3 text-base font-medium text-indigo-600 hover:bg-indigo-50"
>
Learn more
</a>
</div>
</div>
</div>
</div>
)
}`
}}
/>
)}

Read-only mode

You can set one file, multiple files, or the entire Sandpack to read-only. Then, no user can edit your file.

  1. Globally
  2. Based on a single File

Globally:

"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
options={{
readOnly: true,
}}
template="react"
files={{
"/App.js": `export default function app() {
return (<p>Hello, World!</p>)
}`
}}
/>
)}

Based on a single File:

"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
options={{
readOnly: true,
}}
template="react"
files={{
"/App.js": {
code: `export default function app() {
return (<p>Hello, World!</p>)
}`
readOnly: true
}
}}
/>
)}

Custom Entry File

You can specify a custom entry file for the sandbox. The entry file is the starting point of the bundling process.

"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack

customSetup={{
entry: "/main.js",
}}

template="react"
files={{
"/main.js": `export default function app() {
return (<p>Hello, World!</p>)
}`
}}
/>
)}

Options

  1. Layout mode
  2. Navigator
  3. Editor Settings

Layout mode

The Sandpack preset component comes with three layout modes:

  1. preview: (default option), which renders an iframe as a preview component;
  2. tests: which renders a suit-test component;
  3. console: which renders a terminal/console component instead of the preview.
"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
template="node"
options={{
layout: "console", // preview | tests | console
}}
/>
)}

Navigator

By default, Sandpack will show a refresh button on the preview.

With showNavigator, you can toggle on a full browser navigator component with back, forward, and refresh buttons and an input for the URL.

"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
template="react"
options={{
showNavigator: true,
}}
/>
)}

Editor Settings

The Sandpack has some special props for the code editor. With this, you can extend the editor functionality.

  1. showLineNumbers: toggle on/off line numbers in the editor.
  2. showInlineErrors: toggle on/off error of the editor component.
  3. wrapContent: wrap content according to screen width.
  4. editorHeight: By default, the height is 300px, but you can adjust that with the editorHeight prop.
  5. showConsole: show the dev tool component to render the logs;
  6. showConsoleButton: toggle dev tool component.
  7. autorun: The bundling process should start automatically for a component in Sandpack.
  8. autoReload: the component should automatically reload when changes are made to the code.
"use client"

import { Sandpack } from '@codesandbox/sandpack-react';

export function SandboxIDEBasic() {
return (
<Sandpack
options={{
showTabs: true,
showConsoleButton: true,
showConsole: true,
showNavigator: true,
showLineNumbers: true, // default - true
showInlineErrors: true, // default - false
wrapContent: true, // default - false
editorHeight: 764, // default - 300
editorWidthPercentage: 80, // default - 50
}}
theme="dark"
template="react"
files={{
"/App.js": `export default function app() {
return (<p>Hello, World!</p>)
}`
}}
/>
)}

For other options, read the Sandpack documentation. Sandpack also comes with built-in extensions and language server support to extend functionality.

I cover some basic options and configuration; for advanced use cases, stay with the documentation.

Conclusion

The Sandpack is a great library. You can use it for a browser IDE or display code on a website.

Most importantly, users can run the code inside the browser and edit it.

To learn more about frontend developers, reactjs, nextjs, and Linux stuff, follow the frontend web publication on Medium and other updates. You can also follow me on Twitter (X) and Medium.

--

--

Rajdeep Singh
FrontEnd web

JavaScript | TypeScript | Reactjs | Nextjs | Rust | Biotechnology | Bioinformatic | Frontend Developer | Author | https://linktr.ee/officialrajdeepsingh