Using KeyLines with React
Introduction
This start guide shows how to create a React application with a KeyLines chart.
For more information about integrating KeyLines with React, see also the React Integration demo and React Reference documentation.
Note that if you store KeyLines in your source control, you must ensure it's not publicly available. Read more about the Obfuscation Requirements before deploying your application.
Step 1: Create and serve a React app
If you already have an existing project up and running, you can skip this step and continue adding KeyLines from Step 2, replacing my‑react‑app with the name of your project's root directory and integrating the example code into your application code.
If you don't have an existing project, you can create one with Vite. Follow the Vite Getting Started guide for your preferred package manager.
If you're using npm, you can use this quick start command to create a React Vite app:
npm create vite@latest my-react-app -- --template react
Once the process has finished, start a development server:
cd my-react-app
npm install
npm run dev
By default, Vite runs a dev server at http://localhost:5173.
Step 2: Add KeyLines to the app
Download the KeyLines package from the link below and move it to the my-react-app directory.
Request a trial (Required to Download)In the terminal from my-react-app, add KeyLines as a package dependency:
npm install file:./keylines-8.6.0-11643712880.tgz
Step 3: Create a chart
First, update src/index.css to set the dimensions for the KeyLines chart:
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
margin: 0;
}
.chart-container {
width: 100vw;
height: 100vh;
}
Next, open the src/App.jsx file which contains the React component, and replace the contents of this file with a simple KeyLines React chart component:
import { Chart } from 'keylines/react'; // imports the KeyLines React chart component
const data = { // declares chart data - a single node with a label
type: 'LinkChart', // A KeyLines Chart type - must be 'LinkChart'
items: [
{
type: 'node',
id: 'n1',
c: '#43976C', // node colour
t: 'Hello World' // node text label
}
]};
function App() { // renders a chart
let chart;
const changeChart = newChart => { // saves a reference to the created KeyLines chart object
chart = newChart;
};
return (
<Chart
data={data} // loads the data in required KeyLines format
ready={changeChart} // calls the saved chart object
containerClassName="chart-container" // defines the container div for the chart
/>
);
}
export default App;
The Chart
component defined in src/react-keylines.jsx
wraps the underlying KeyLines chart object.
The ready callback supplied to the component is called
with the KeyLines chart object.
Here the changeChart
callback saves a reference to the KeyLines chart object.
You should now see a simple KeyLines chart in your browser:
Charts have a range of native options such as navigation to pan and zoom or overview window icon at the bottom right corner to toggle a chart overview.
Step 4: Add and parse the data
Replace the existing data
object in src/App.jsx
with this data:
const data = {
person: [
{ name: 'Jenny', teamId: 1 },
{ name: 'Rosie', teamId: 0 },
{ name: 'Peter', teamId: 0 },
{ name: 'Sam', teamId: 1 },
],
messages: [
{ from: 'Jenny', to: 'Sam', amount: 17 },
{ from: 'Sam', to: 'Jenny', amount: 12 },
{ from: 'Sam', to: 'Peter', amount: 1 },
{ from: 'Rosie', to: 'Jenny', amount: 2 },
{ from: 'Peter', to: 'Rosie', amount: 7 },
],
};
This dataset details messages between two teams of people.
KeyLines accepts a ChartData object, which defines an array of chart items and their attributes. This means that we will need to parse our raw data to a KeyLines chart object. This is how we've defined our data model:
- People are represented by nodes.
Nodes require a
type: 'node'
and a uniqueid
. The default node colour is transparent, so we will also set thec
property. - Messages between people are represented as links.
Links require a
type: 'link'
, a uniqueid
, andid1
andid2
properties whose values are ids of nodes at each link end.
To parse the data, add this function inside the App()
function:
function convertDataToKeyLinesFormat(data) {
const items = [];
data.person.forEach(({ name }) => { // defines people as nodes
items.push({
id: name,
type: 'node',
c: '#43976C',
});
});
data.messages.forEach(({ from, to }) => { // defines messages as links
items.push({
type: 'link',
id: `link_${from}_${to}`,
id1: from,
id2: to,
});
});
return { type: 'LinkChart', items }; // adds 'LinkChart' required by KeyLines
}
And update the render function to return the parsed data:
return (
<Chart
data={convertDataToKeyLinesFormat(data)} // loads the parsed data and runs the default layout
ready={changeChart}
containerClassName="chart-container"
/>
);
Note that react-keylines.jsx automatically performs a layout when loading new data. By default this is the organic layout, which is a versatile force-directed layout algorithm that is especially great for large datasets and complex networks, but there are also other layouts you can explore.
Your application and developer console should now be clear of any errors and you should see this network in the browser:
Our data model is now visualised as nodes and links, but it's difficult to distinguish the individual items on the chart. To address this, we will incorporate details as styling in the next step.
Step 5: Add details with styling
KeyLines offers a variety of styling options for nodes and links. In our chart, we will use node and link styling as a way of showing item metadata.
To style the nodes, we will:
- Use the c property to set a different colour for each team
- Use the t property to add a text label and style it
To do this, update the first part of the convertDataToKeyLinesFormat
function
where we have defined the people as nodes:
data.person.forEach(({ name, teamId }) => {
items.push({
id: name,
type: 'node',
c: [ '#43976C','#ff6f61' ][teamId], // node colour by team
t: { fbc: 'transparent', fs: 'auto', fc: 'white', t: name }, // white backgroundless text sized to fit the node
});
});
To style the links, we will:
- Use the w property to scale the link widths based on the number of messages sent
- Use the a2 property to set a direction arrow that identifies the direction of the communication
To do this, update the second part of the convertDataToKeyLinesFormat
function
where we have defined the messages as links:
data.messages.forEach(({ from, to, amount }) => {
items.push({
type: 'link',
id1: from,
id2: to,
id: `link_${from}_${to}`,
a2: true, // arrow pointing to the recipient
w: Math.pow(amount, 0.8) // link width scalable by amount to the power of 0.8
});
});
The chart now reveals which individuals belong to a specific group (team) and the strength of the relationship between the individuals (the amount of communication).
Step 6: Customise the chart options
Now let's customise some chart options. The chart options APIs can be used to change styling, display and interaction defaults of the chart as an element that integrates into your application.
Add an object with options to src/App.jsx:
const options = {
selectedNode: { ha0: { c: "#f5bd1f", r: 37, w: 8 } }, // creates a halo around selected node
controlTheme: 'dark' , // turns navigation controls and overview window to dark mode
backColour: '#1b2327', // a background colour
};
And in the render function, add the options object that will override the default component options with your new options:
options={options} // updates the chart with new options
The resulting chart now looks like this when the 'Peter' node is selected:
Step 7: Add event handling
In this step, let's add some code to respond when the user clicks an item on the chart.
KeyLines lets you respond to virtually any user event on the chart using chart events.
Add a click handler function responding to a
click event on the chart
to src/App.jsx after changeChart
:
const clickHandler = ({ id }) => {
console.log(`you clicked on ${id}`);
}
And in the render function, add the click function that will attach the handler:
click={clickHandler} // attaches the handler for click event
Try clicking chart items, navigation controls or the chart background. In the developer tools console you'll see that a string containing the id of the clicked item or navigation control is passed to the click handler, or null if you click on the chart background.
Step 8: Add foregrounding on selection
Now let's set a foregrounding behaviour that highlights the user-selected item and its immediate neighbours, which is particularly helpful for large charts with densely connected nodes.
Add a selection change handler function responding to a
selection-change event
to src/App.jsx after changeChart
:
const selectionHandler = () => {
const itemIds = chart.selection();
const selectedItems = chart.getItem(itemIds); // Ensure we have clicked on a link or node, not the navigation control
if (selectedItems.length !== 0) {
const neighbours = chart.graph().neighbours(itemIds); // Foreground the selected item and its neighbours
chart.foreground(
(item) => itemIds.includes(item.id) || neighbours.nodes.includes(item.id)
);
} else {
// Clicked on background - restore all items to the foreground
chart.foreground(() => true);
}
}
And in the render function, add the selection-change function that will attach the handler:
selection-change={selectionHandler} // attaches the handler for selection-change event
The new selectionHandler
function uses chart.getItem()
to check whether the clicked id belongs to a node or a link in the chart.
If it does, then we use chart.graph().neighbours() to find the nodes connected to the clicked item, and then call chart.foreground() to put them in the foreground, and other chart items in the background.
If the user clicked on something else, such as the chart background, then we foreground all the chart items.
Next steps
This is just the beginning of what KeyLines can offer.
You can continue reading about the features from this tutorial in Chart Basics, Layout Basics and Events Basics.
Have a look also at our Demos and our API Reference, or visit our blog for interesting articles about graph visualisation.
Here's a few suggestions on where to go next if you're interested in...
- More information about KeyLines and React? Try the React Integration demo and the React Reference documentation.
- Adding font icons to items in your chart? Head to Fonts and Font Icons for help.
- Grouping nodes or links to summarise your chart? Take a look at Combos and Aggregate Links.
- Filtering chart by time or learning about changes over time? Read about the KeyLines Time Bar component.
- Running graph analysis or social network analysis? Read about Graph Engine and Graph Centrality.