DomParfitt / graphviz-react

React component for displaying Graphviz graphs
MIT License
103 stars 21 forks source link
graphviz react

graphviz-react

Continuous Integration

  1. Overview
  2. Install
  3. Usage
    1. Props
    2. NextJS
    3. Examples
  4. Dependencies

Overview

graphviz-react provides a simple to use component for rendering Graphviz objects in React. It effectively acts as a React-flavoured wrapper over the d3-graphviz library, providing a uniform way to use the renderer. graphviz-react is written in Typescript and provides typing declarations.

A demo of this component can be found here.

Install

From the root directory of your React project run the following command.

npm install graphviz-react

N.B. There is currently an issue with react-scripts and the viz.js package used by d3-graphviz that causes heap overflows when running react-scripts start and react-scripts build. To get around this set --max_old_space_size=4096 when running. This can be done by either running the following:

NODE_OPTIONS=--max_old_space_size=4096 npm run start

or by adding the flag to the relevant commands in the scripts section of your package.json as such:

"scripts": {
  "start": "react-scripts --max_old_space_size=4096 start",
  "predeploy": "react-scripts --max_old_space_size=4096 build",
}

Usage

Add an import to the top of the component you wish to use Graphviz with.

import { Graphviz } from 'graphviz-react';

To render a Graphviz component as part of an existing React component simply include the Graphviz tag as part of that component's render function along with the dot prop.

Props

The following props are available to the component:

dot: string
options?: GraphvizOptions
className?: string

NextJS

By default NextJS pre-renders every page. This causes issues with graphviz-react as it relies on attaching rendered graphs to DOM components, which are only available client-side, not server-side.

The workaround for this is to use dynamic imports to import the package without server-side rendering on pages where the component is required:

import dynamic from 'next/dynamic';

const Graphviz = dynamic(() => import('graphviz-react'), { ssr: false });

const GraphvizPage = () => {
  const dot = 'graph{a--b}';

  return <Graphviz dot={dot} />;
}

export default GraphvizPage;

Examples

The below shows a simple React component using the Graphviz component to render a simple DOT string (GraphViz Pocket Reference).

<Graphviz dot={`graph {
  grandparent -- "parent A";
  child;
  "parent B" -- child;
  grandparent --  "parent B";
}`} />
<Graphviz dot={`digraph {
  a -> b;
  c;
  d -> c;
  a -> d;
}`} />

Dependencies

  1. React
  2. d3-graphviz