React Components
The LikeC4 React library embeds diagrams into your applications. There are several ways to use it:
- Bundled: components from
likec4/react, you prepare the model yourself - Generated components: the CLI generates components bound to your model
- Vite plugin: the same components from a virtual module, updated as you edit the sources
- Library:
@likec4/diagramwith your bundler, you manage the styles
Installation
Section titled “Installation”You must have react and react-dom installed.
Add likec4:
npm i likec4pnpm add likec4yarn add likec4bun add likec4Bundled
Section titled “Bundled”This is the easiest way to use the library.
The diagram renders inside the shadow DOM, includes all dependencies, and handles styling.
LikeC4ModelProvider
Section titled “LikeC4ModelProvider”The diagram requires an instance of LikeC4Model.Layouted to render.
You need to prepare it and wrap your diagram with the LikeC4ModelProvider component.
Below are examples of how to prepare the model:
- Using CLI codegen
- Using source files
- Using Model Builder
Prepare model with code generation:
likec4 codegen model --outfile ./likec4-model.tsThen:
import { LikeC4ModelProvider } from 'likec4/react'// import model from generated fileimport { likec4model } from './likec4-model.ts'
function App() { return ( <LikeC4ModelProvider likec4model={likec4model}> {/* ... */} </LikeC4ModelProvider> )}The LikeC4 API parses and lays out the sources, but runs only in Node.js. Run it as a build step and save the model data to a JSON file:
import { LikeC4 } from 'likec4'import { writeFile } from 'node:fs/promises'
// or LikeC4.fromSource(`...`) to parse a stringawait using likec4 = await LikeC4.fromWorkspace('./architecture')const model = await likec4.layoutedModel()
await writeFile('./src/likec4-model.json', JSON.stringify(model.$data))Then create the model from this file in your app:
import { LikeC4Model } from 'likec4/model'import { LikeC4ModelProvider } from 'likec4/react'import data from './likec4-model.json'
const likec4model = LikeC4Model.fromDump(data)
function App() { return ( <LikeC4ModelProvider likec4model={likec4model}> {/* ... */} </LikeC4ModelProvider> )}You can prepare the model with the Builder, then lay it out with layoutLikeC4Model:
import { LikeC4ModelProvider } from 'likec4/react'import { Builder } from "likec4/model/builder"import { layoutLikeC4Model } from "likec4/layouts"
const computedModel = Builder .specification({ elements: {46 collapsed lines
actor: { style: { shape: 'person', }, }, system: {}, component: {}, }, relationships: { likes: {}, }, tags: ['tag1', 'tag2', 'tag1'], }) .model(({ actor, system, component, relTo, rel }, _) => _( actor('alice'), actor('bob'), rel('alice', 'bob', { tags: ['tag1'], // you get code completion for tags kind: 'likes', // code completion for kind }), system('cloud', { tags: ['tag1', 'tag2'] }).with( component('backend').with( component('api'), component('db'), // code completion for relationships rel('cloud.backend.api', 'cloud.backend.db') ), component('frontend').with( relTo('cloud.backend.api') ), ), ) ) .views(({ view, viewOf, $include, $style }, _) => _( view('index', 'Index').with( $include('cloud.*'), ), viewOf('ui', 'cloud.ui').with( $include('* -> cloud.**'), $style('cloud.ui', { color: 'red' }), ), ) ) .toLikeC4Model()
// The Builder returns a computed model. To render it, you need to lay it outconst likec4model = await layoutLikeC4Model(computedModel)
function App() { return ( <LikeC4ModelProvider likec4model={likec4model}> {/* ... */} </LikeC4ModelProvider> )}In the examples below, likec4model is the model prepared in one of the ways above.
LikeC4View
Section titled “LikeC4View”import { LikeC4View, LikeC4ModelProvider } from 'likec4/react'
function App() { return ( <LikeC4ModelProvider likec4model={likec4model}> <LikeC4View viewId="index" /> {/* Possible to have multiple views */} <LikeC4View viewId="ui" browser={false} /> </LikeC4ModelProvider> )}A click on the view opens it in a popup browser, where you can explore the model.
| Property | Description |
|---|---|
viewId |
View to display |
layoutType |
manual (default) uses the manual layout if the view has one, auto ignores it |
browser |
Open the popup browser on click (default true) |
pannable |
Enable panning (default false) |
zoomable |
Enable zooming (default false) |
colorScheme |
light or dark, default follows the system preferences |
injectFontCss |
Inject CSS with the IBM Plex Sans Variable font from CDN (default true).Set to false to load the font yourself |
where |
Show only some elements and relationships, see Filter |
renderIcon |
Render element icons, see Icons |
See LikeC4ViewProps for all properties.
ReactLikeC4
Section titled “ReactLikeC4”LikeC4View renders views from your model and allows exploration in the popup browser.
This component works in most use cases, but if you need more control and want to react to events, use ReactLikeC4:
import { ReactLikeC4, LikeC4ModelProvider } from 'likec4/react'import { useState } from 'react'
function App() { const [viewId, setViewId] = useState('index') return ( <LikeC4ModelProvider likec4model={likec4model}> <ReactLikeC4 viewId={viewId} pannable zoomable={false} keepAspectRatio showNavigationButtons enableDynamicViewWalkthrough={false} enableElementDetails enableRelationshipDetails onNavigateTo={setViewId} onNodeClick={(node) => console.log('clicked', node.id)} /> </LikeC4ModelProvider> )}See LikeC4Diagram.props.ts for available properties and event handlers.
Filter
Section titled “Filter”where is the same as the view predicate, but applies dynamically and lets you show or hide elements depending on the context.
Both LikeC4View and ReactLikeC4 accept it:
// Keeps elements and relationships where:// - tag is not 'legacy'// - and// - tag is 'v1' or 'v2'<LikeC4View viewId="index" where={{ and: [ { tag: { neq: 'legacy' } }, { or: [ { tag: { eq: 'v1' } }, { tag: { eq: 'v2' } } ] } ] }}/>Layout stays the same, i.e. elements are not rearranged.
Be aware, where applies both to elements and relationships.
Available hooks inside LikeC4View or ReactLikeC4:
import { useLikeC4Model, useLikeC4Specification, useLikeC4ViewModel, useEnabledFeatures, useCurrentViewId,
// Diagram API useDiagram, useOnDiagramEvent,
// Select from the diagram state useDiagramSelector, selectDiagramSnapshot,} from 'likec4/react'If you use built-in icons, install @likec4/icons:
import type { ElementIconRenderer } from 'likec4/react'import { LikeC4ModelProvider, LikeC4View, ReactLikeC4 } from 'likec4/react'import { lazy, Suspense } from 'react'
// Better to lazy load icons, bundle is quite large at the momentconst Icon = lazy(async () => { const { IconRenderer } = await import('@likec4/icons/all') return { default: IconRenderer }})
const IconRenderer: ElementIconRenderer = (props) => ( <Suspense> <Icon {...props} /> </Suspense>)
function App() { return ( <LikeC4ModelProvider likec4model={likec4model}> <LikeC4View viewId="index" renderIcon={IconRenderer} /> {/* Same for ReactLikeC4 */} <ReactLikeC4 viewId="ui" renderIcon={IconRenderer} /> </LikeC4ModelProvider> )}Generated components
Section titled “Generated components”The CLI generates a JavaScript module with LikeC4View and ReactLikeC4 bound to your model:
they don’t need LikeC4ModelProvider, the icons are bundled, and viewId is typed with the IDs of your views.
Generate
Section titled “Generate”npx likec4 gen react -o ./src/likec4.generated.jspnpx likec4 gen react -o ./src/likec4.generated.jsyarn dlx likec4 gen react -o ./src/likec4.generated.jsbunx likec4 gen react -o ./src/likec4.generated.jsgenerate and codegen are aliases of gen:
likec4 generate react -o ./src/likec4.generated.jslikec4 codegen react -o ./src/likec4.generated.jsThe command writes the module and its type declarations next to it (likec4.generated.js and likec4.generated.d.ts).
| Option | Description |
|---|---|
[path] |
Directory with LikeC4 sources (default is the current directory) |
-o, --outfile |
Output file, must be .js, .mjs or .jsx (default is likec4-views.js in the workspace) |
-p, --project |
Project to generate, by name or path, in a multi-project workspace |
--customization |
Bundle the UI customization into the components (experimental) |
--app-config |
Path to the app config, --no-app-config to ignore it |
--use-dot |
Use local Graphviz binaries (“dot” on PATH) instead of the bundled WASM |
--use-core-package |
Import types from @likec4/core instead of likec4 in the .d.ts |
Run likec4 gen react --help for all options.
Exports
Section titled “Exports”| Export | Description |
|---|---|
LikeC4View |
LikeC4View with the model and icons |
ReactLikeC4 |
ReactLikeC4 with the model and icons |
LikeC4ModelProvider |
Provides the model to the components and hooks from likec4/react, takes only children |
likec4model |
The model, LikeC4Model instance |
useLikeC4Model() |
Returns the model, works outside of LikeC4ModelProvider |
useLikeC4View(viewId) |
Returns the layouted view |
isLikeC4ViewId(value) |
Checks if the value is an ID of a view |
RenderIcon |
Renders the bundled icons, pass it to renderIcon |
LikeC4ViewProps, ReactLikeC4Props |
Types of the component properties |
$ViewId, $ElementId, $Tag, … |
Types of the model IDs and kinds |
The generated components accept the same properties as their bundled counterparts, except the model:
import { LikeC4View } from './likec4.generated'
const App = () => { return <LikeC4View viewId="index" />}import { ReactLikeC4, type $ViewId } from './likec4.generated'import { useState } from 'react'
const App = () => { const [viewId, setViewId] = useState<$ViewId>('index') return ( <ReactLikeC4 viewId={viewId} pannable onNavigateTo={setViewId} /> )}To use the components from likec4/react with the generated model, pass likec4model and RenderIcon:
import { ReactLikeC4, LikeC4ModelProvider } from 'likec4/react'import { RenderIcon, likec4model } from './likec4.generated'
const App = () => { return ( <LikeC4ModelProvider likec4model={likec4model}> <ReactLikeC4 viewId="index" renderIcon={RenderIcon} onEdgeClick={(edge) => console.log('clicked', edge.id)} /> </LikeC4ModelProvider> )}Library
Section titled “Library”If you want to use the package as a library with your bundler, you need to manage the CSS yourself.
For this, add @likec4/diagram instead of likec4:
npm i @likec4/diagrampnpm add @likec4/diagramyarn add @likec4/diagrambun add @likec4/diagramThe library uses Mantine. If you already use it and have MantineProvider in scope, the LikeC4 diagram will use it.
Otherwise, it will wrap itself with MantineProvider.
Even if you are not using Mantine in your app, its styles are required for the diagrams to work (don’t worry, Mantine is tree-shakable).
Here are the options:
With bundled styles
Section titled “With bundled styles”-
Import all styles
@import '@likec4/diagram/styles.css'This includes all styles, including the Mantine styles.
-
If you are using Mantine
@layer reset, base, mantine, xyflow, tokens, recipes, utilities;@import "@mantine/core/styles.layer.css";@import "@likec4/diagram/styles-min.css"; -
Font.
LikeC4Diagram usesIBM Plex Sans Variableby default.
You can bundle it, import it from fontsource, from any other CDN, or use:@import '@likec4/diagram/styles-font.css'To use another font, set the
--likec4-app-fontvariable. The layout is computed with the metrics of IBM Plex Sans, so with another font the labels may fit differently.:root {--likec4-app-font: 'Inter Variable', sans-serif;}
With PandaCSS
Section titled “With PandaCSS”Check the PandaCSS docs for full setup instructions.
LikeC4 provides a preset.
npm i @likec4/styles @likec4/style-presetpnpm add @likec4/styles @likec4/style-presetyarn add @likec4/styles @likec4/style-presetbun add @likec4/styles @likec4/style-presetConfigure your panda.config.ts:
import { defineConfig } from '@pandacss/dev'
export default defineConfig({ include: [ 'src/**/*.{ts,tsx}', // Include likec4 diagram source code to get the styles './node_modules/@likec4/diagram/panda.buildinfo.json', ], importMap: [ '@likec4/styles', ], presets: [ '@likec4/style-preset', ], theme: { extend: { // Here you can override/extend the theme }, },})Your global CSS should look like this:
@layer reset, base, mantine, xyflow, tokens, recipes, utilities;@import "@mantine/core/styles.layer.css";@import "@likec4/diagram/styles-xyflow.css";@import "@likec4/diagram/styles-font.css";Render a view
Section titled “Render a view”Import the components from @likec4/diagram.
LikeC4Diagram takes the view to render (DiagramView) and the same properties as ReactLikeC4:
import { LikeC4Diagram, LikeC4ModelProvider, useLikeC4ViewModel } from '@likec4/diagram'
function LikeC4View({ viewId }: { viewId: string }) { const view = useLikeC4ViewModel(viewId) return ( <LikeC4Diagram view={view.$view} pannable zoomable={false} showNavigationButtons enableDynamicViewWalkthrough={false} enableElementDetails enableRelationshipDetails /> )}
function App() { return ( <LikeC4ModelProvider likec4model={likec4model}> <LikeC4View viewId="index" /> </LikeC4ModelProvider> )}Keyboard shortcuts
Section titled “Keyboard shortcuts”Focused diagrams support keyboard zoom shortcuts. Click a diagram or tab into it first; while the diagram is focused, these shortcuts control diagram zoom instead of browser page zoom. Tab out of the diagram to use browser page zoom.
| Shortcut | Action |
|---|---|
Ctrl/Cmd + + or = |
Zoom in |
Ctrl/Cmd + - or _ |
Zoom out |
Ctrl/Cmd + 0 |
Reset the viewport |
Customization
Section titled “Customization”UI slots (experimental)
Section titled “UI slots (experimental)”There are two customization layers:
- UI slots — replace or wrap registered shell components
- Node renderers — customize how nodes are drawn (see below)
import { CustomizationProvider, defineCustomComponents, LikeC4ModelProvider, LikeC4View,} from 'likec4/react'
const components = defineCustomComponents(({ wrap }) => ({ LogoSvg: (props) => <svg {...props}><text>Brand</text></svg>, LikeC4View: wrap(({ Original, ...props }) => ( <Original {...props} pannable={false} /> )),}))
function App() { return ( <CustomizationProvider components={components}> <LikeC4ModelProvider likec4model={likec4model}> <LikeC4View viewId="index" /> </LikeC4ModelProvider> </CustomizationProvider> )}- replace — pass a component that receives the slot’s original props
- wrap — use
wrap; your component receives{ Original, ...props }
Place CustomizationProvider above the diagram tree. Ordering relative to LikeC4ModelProvider does not matter. Prefer a module-scoped components constant so overrides stay HMR-friendly.
With @likec4/diagram, import the same helpers from @likec4/diagram/custom.
See UI customization for the list of slots, and for applying the overrides to the LikeC4 application (CLI, Vite plugin) from a file.
Children and portals
Section titled “Children and portals”You can render any component inside LikeC4Diagram
(or LikeC4View/ReactLikeC4 if you are using bundle):
import { LikeC4Diagram, useLikeC4ViewModel } from '@likec4/diagram'import { Panel, ViewportPortal } from '@xyflow/react'
function Diagram({ viewId }: { viewId: string }) { const view = useLikeC4ViewModel(viewId) return ( <LikeC4Diagram view={view.$view}> <YourComponent />
{/* You can use components from xyflow */} <Panel position="top-center"> <p>Your component as a panel</p> <a href="https://reactflow.dev/examples">Check examples</a> </Panel>
<ViewportPortal> <div style={{ transform: 'translate(100px, 100px)', position: 'absolute', }}> This div is positioned at [100, 100] on the diagram canvas </div> </ViewportPortal> </LikeC4Diagram> )}Custom node renderers
Section titled “Custom node renderers”LikeC4Diagram can use custom node renderers.
Compose custom node renderers using primitives from likec4/react
(or from @likec4/diagram/custom, if you use the library).
See customNodes.tsx for examples.
import { LikeC4Diagram, useLikeC4ViewModel } from '@likec4/diagram'import { ElementActions, elementNode, ElementNodeContainer, ElementShape, ElementData,} from '@likec4/diagram/custom'import { IconPlus } from '@tabler/icons-react'
const customNodes = { element: elementNode(({ nodeProps, nodeModel }) => ( <ElementNodeContainer nodeProps={nodeProps}> <ElementShape {...nodeProps} /> <ElementData {...nodeProps} /> {/* Add extra buttons */} <ElementActions {...nodeProps} extraButtons={[ { key: 'plus', icon: <IconPlus />, onClick: () => console.log('extra'), }, ]} /> {/* Add extra info */} <div style={{ position: 'absolute', bottom: 0 }}> {nodeModel.element.getMetadata('your-attr')} </div> </ElementNodeContainer> )),}
function Diagram({ viewId }: { viewId: string }) { const view = useLikeC4ViewModel(viewId) return ( <LikeC4Diagram view={view.$view} renderNodes={customNodes} /> )}You can also use hooks to access the model and diagram API.
Custom styles
Section titled “Custom styles”LikeC4Diagram uses PandaCSS for styling. Use the LikeC4 preset to customize the styles.