Pre loader

 How to Make Charts in React from Scratch?

 How to Make Charts in React from Scratch?

When it comes to making React charts from scratch, you have two choices. You can either use a library that provides React support or create your own wrapper around any JavaScript library. We recommend you use scichart-react, an open source React component wrapper for SciChart.js.

For basic and complex charts, using a chart library that supports React makes the chart-building experience easier to manage and unlocks more creative and high-performance data possibilities.

How to Build React Charts from Scratch in SciChart?

With SciChart, the approach to building React Charts is straightforward. Once you’ve imported the SciChart React library from the module, you’ll have access to all the resources and features to start building. We’re detailing the crucial steps to get started, along with code examples.

Setting up a New React Project with SciChart

A recommended way to set up a new project is to use React, Webpack, and TypeScript.

package.json
webpack.config.js
tsconfig.json
index.html
index.tsx

package.json

{
    "name": "blog-scichart-react",
    "version": "1.0.0",
    "description": "scichart-react vs scichart",
    "main": "src/index.tsx",
    "scripts": {
        "build": "webpack --mode production",
        "start": "ts-node server",
        "dev": "webpack-dev-server --mode development"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
        "react": "^18.3.1",
        "react-dom": "^18.3.1",
        "scichart": "^3.5.711",
        "scichart-react": "^0.1.9",
        "ts-node": "^10.9.2"
    },
    "devDependencies": {
        "@types/react": "^18.3.18",
        "@types/react-dom": "^18.3.5",
        "copy-webpack-plugin": "^12.0.2",
        "prettier": "^3.4.2",
        "ts-loader": "^9.5.1",
        "typescript": "^5.1.6",
        "webpack": "^5.97.1",
        "webpack-cli": "^5.1.4",
        "webpack-dev-server": "^5.2.0"
    }
}

webpack.config.js

const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
  entry: "./src/index.tsx",
  performance: {
    hints: false
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/
      },
    ]
  },
  resolve: {
    extensions: [".js", ".ts", ".tsx"]
  },
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "build")
  },
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: "src/index.html", to: "" },
        { from: "node_modules/scichart/_wasm/scichart2d.data", to: "" },
        { from: "node_modules/scichart/_wasm/scichart2d.wasm", to: "" },
        { from: "node_modules/scichart/_wasm/scichart3d.data", to: "" },
        { from: "node_modules/scichart/_wasm/scichart3d.wasm", to: "" },
      ]
    })
  ]
};

tsconfig.json

{
    "compilerOptions": {
        "outDir": "./build",
        "sourceMap": true,
        "strict": true,
        "noImplicitAny": true,
        "strictNullChecks": false,
        "strictFunctionTypes": true,
        "strictBindCallApply": true,
        "strictPropertyInitialization": false,
        "noImplicitThis": true,
        "alwaysStrict": true,
        "noUnusedLocals": false,
        "noUnusedParameters": false,
        "noImplicitReturns": true,
        "noFallthroughCasesInSwitch": true,
        "module": "commonjs",
        "target": "es6",
        "jsx": "react-jsx",
        "allowJs": true,
        "typeRoots": [
            "./src/types", "./node_modules/@types"],
        "esModuleInterop": false,
        "skipLibCheck": false,
        "forceConsistentCasingInFileNames": true
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules"
    ]
}

index.html

<html lang="en-us">
    <head>
        <meta charset="utf-8" />
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
        <title>SciChart demo</title>
        <script async type="text/javascript" src="bundle.js"></script>
    </head>
    <body></body>
</html>

index.tsx

import { createRoot } from 'react-dom/client';
import App from './App';

// Clear the existing HTML content
document.body.innerHTML = '<div id="app"></div>';

const root = createRoot(document.getElementById('app'));
root.render(<App />);

Create scichart-react Chart with Config (Builder) API

The builder API is handy for sharing charts because JSON configuration is self-sufficient.

import {
    ESeriesType,
    EThemeProviderType
} from 'scichart';
import { SciChartReact } from 'scichart-react';

// 1. Via builder API
const chartConfig = {
    surface: {
        theme: { type: EThemeProviderType.Dark },
        title: 'scichart-react via builder API',
        titleStyle: {
            fontSize: 20,
        },
    },
    series: {
        type: ESeriesType.SplineMountainSeries,
        options: {
            strokeThickness: 4,
            stroke: '#216939',
            fillLinearGradient: {
                startPoint: { x: 0, y: 0 },
                endPoint: { x: 1, y: 1 },
                gradientStops: [
                    { offset: 0.3, color: '#2d2169' },
                    { offset: 1, color: 'transparent' },
                ],
            },
        },
        xyData: { xValues: [0, 1, 2, 3, 4], yValues: [3, 6, 1, 5, 2] },
    },
};

export default function SciChartReactDemo() {
    // @ts-ignore
    return ;
}

Create scichart-react Chart with Programmatic API

Another alternative is to use the Programmatic API. It is the primary scichart.js API with slightly better TypeScript support and a complete set of features.

import {
    EThemeProviderType,
    NumericAxis,
    SciChartSurface,
    SplineMountainRenderableSeries,
    XyDataSeries,
} from 'scichart';
import { SciChartReact } from 'scichart-react';

// 2. Via Initialization function
const chartInitializationFunction = async (rootElement: string | HTMLDivElement) => {
    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
        theme: { type: EThemeProviderType.Dark },
        title: 'scichart-react via initialization function',
        titleStyle: {
            fontSize: 20,
        },
    });

    sciChartSurface.xAxes.add(new NumericAxis(wasmContext));
    sciChartSurface.yAxes.add(new NumericAxis(wasmContext));
    sciChartSurface.renderableSeries.add(
        new SplineMountainRenderableSeries(wasmContext, {
            dataSeries: new XyDataSeries(wasmContext, {
                xValues: [0, 1, 2, 3, 4],
                yValues: [3, 6, 1, 5, 2],
            }),
            strokeThickness: 4,
            stroke: '#216939',
            fillLinearGradient: {
                startPoint: { x: 0, y: 0 },
                endPoint: { x: 1, y: 1 },
                gradientStops: [
                    { offset: 0.3, color: '#2d2169' },
                    { offset: 1, color: 'transparent' },
                ],
            },
        }),
    );

    return { sciChartSurface };
};

export default function SciChartReactDemo() {
    return ;
}

 

Creating a React Chart in SciChart Without the Wrapper

The third option would be to create the chart without scichart-react wrapper using only scichart.js. As you can see, the code is not very different from the previous example.

import { useEffect, useRef } from 'react';
import {
    NumericAxis,
    SciChartJSDarkTheme,
    SciChartSurface,
    SplineMountainRenderableSeries,
    XyDataSeries,
} from 'scichart';

async function createChart(divElementId: string | HTMLDivElement) {
    const { sciChartSurface, wasmContext } = await SciChartSurface.create(divElementId, {
        theme: new SciChartJSDarkTheme(),
        title: 'Basic Chart just with scichart',
        titleStyle: {
            fontSize: 20,
        },
    });

    const xAxis = new NumericAxis(wasmContext);
    const yAxis = new NumericAxis(wasmContext);

    sciChartSurface.xAxes.add(xAxis);
    sciChartSurface.yAxes.add(yAxis);

    const xyDataSeries = new XyDataSeries(wasmContext, { xValues: [0, 1, 2, 3, 4], yValues: [3, 6, 1, 5, 2] });
    const splineMountainSeries = new SplineMountainRenderableSeries(wasmContext, {
        strokeThickness: 4,
        stroke: '#216939',
        fillLinearGradient: {
            startPoint: { x: 0, y: 0 },
            endPoint: { x: 1, y: 1 },
            gradientStops: [
                { offset: 0.3, color: '#2d2169' },
                { offset: 1, color: 'transparent' },
            ],
        },
        dataSeries: xyDataSeries,
    });
    sciChartSurface.renderableSeries.add(splineMountainSeries);

    return { sciChartSurface };
}

export default function SciChartPureDemo() {
    const chartId = 'chartId';
    const chartRef = useRef<SciChartSurface>();

    useEffect(() => {
        createChart(chartId).then((res) => (chartRef.current = res.sciChartSurface));
        return () => chartRef.current?.delete();
    }, []);

    return <div id={chartId} style={{ width: 800 }} />;
}

Which Option Should You Use to Build Your React Charts?

Creating React charts is easy with scichart.js, and there are several options for doing it. Creating a chart using the scichart-react npm module is the easiest; any developer with React experience can use it immediately. The Builder API allows for easy sharing of charts between developers. The programmatic approach leverages the power of the primary API, and if you need even more control, you can use scichart.js in React directly without the scichart-react wrapper.

Should You Use the React Wrapper?

You don’t technically need a library to produce React charts, making this an enticing choice for many organizations and developers. However, both simple and sophisticated charts benefit from a library that offers a reliable React wrapper, supports React chart types, and provides an abundance of examples.

The SciChart React wrapper makes for an easy start. However, most examples don’t use the wrapper and if you’re creating more sophisticated, complex charts, it can be easier to not use the wrapper.

All the Resources you Need to Make React Charts Using SciChart

If you’re an experienced developer, you’re unlikely to have questions about React, but rather questions about the SciChart library itself. Most (if not all) of the answers you need can be found in the documentation or on our forums.

Whether you’re new or experienced in developing React charts and dashboards, the below resources should help you get started with ease.

Browse React Demos & GitHub Code

We recommend starting with our React demos and going through to the GitHub source code to try it out. Then look at the SciChart documentation and CodePen for specific examples. Also look at CodeSandbox and SciChart.JS.Examples on GitHub for even more React examples that you can clone and run locally.

With over 100 React demos and chart types, you may wonder what type of chart you should use to visualize your data in the most effective way. Visit our blog on popular React charts for inspiration.

Visit the demo.scichart website and select the React framework from the drop-down to view your chart options.

The clickable buttons at the top from left to right are as follows:

  • Get It Free: Sign up for our free community edition for free, unlimited access to our charts for non-commercial use.
  • Docs: Access the documentation for the example you’re currently viewing.
  • Code Sandbox: View the chart in CodeSandbox.
  • GitHub Logo: By clicking on GitHub’s Octocat logo (a cross between a cat and an octopus), you can visit the chart in GitHub.
  • npm Logo: Click the npm logo to go to npm (this is the easiest way to create a React chart).

Install the SciChart React Wrapper

From the GitHub SciChart React or npm registry page, you can install the SciChart React wrapper and import all your classes and chart types.

Create Component & Select Properties

When you’re ready to build your chart, create a component and select your properties, such as style and configuration.

Get Started With SciChart React

How to Leverage SciChart’s Extensive Documentation?

How to use and locate SciChart documentation and make the most of it. Add description about the best way to use these resources. Have Examples, SciChart demo and documentation and TypeDoc, which includes API documentation if someone wants to inspect properties or a class. Inspect data labels and descriptions of the property. Best place to start is SciChart demo website to see how different chart types look.

How to manage data when there are many elements on the page is another question you may have. That’s where the flexible API comes in handy. With endless customizations for styling, annotations and interactions, how and what you display is entirely in your hands.

How to Find a Suitable Chart Library for React Charts?

Before you even think about building a React chart or dashboard, you need to consider what chart library or software you’ll use. This should not be chosen on a whim, and while there are plenty of popular free options available that don’t require a licence, you can probably guess they have their drawbacks and lack certain qualities that may be integral to the success of your data visualization project, typically relating to performance requirements.

Your choice of software partially depends on the type of chart needed. Sometimes it is easier to use a library without React support if it fits your requirements. However, it is possible to find all the elements in one software solution.

  • Available Features

    Before choosing a library, explore the available features, API, and whether it’s easy to use. You’ll want to be confident that the necessary chart types for your project are supported, so the chart developers aren’t left scratching their heads or feeling frustrated when they can’t find the code they need. Give your developers the tools they need to succeed, and you’ll be rewarded with high-performance charts and visualizations delivered to your schedule and budget.

  • Chart Updates

    Another consideration that often gets overlooked is how often the chart updates are published.

    Once a month is best practice. Avoid ones that haven’t been updated for years. You’ll often find open-source software ticks the boxes of simplicity from a user’s perspective, but then you see the last chart update was years ago, meaning you won’t get the best performance or compatibility with more modern devices.

  • Performance: Open Source vs. Paid Chart Libraries

    Open-source platforms may look like the popular kid in school, but look past the surface and there are solutions that get overlooked but offer so much more from a flexibility, customization, and performance perspective.

    Think rendering in true real-time, with no lag across devices. Think native cross-platform charts with support for JavaScript, React, WPF, iOS, Android, and MacOS. We could go on and on with the benefits of choosing a licence with a high-powered 64-bit chart library from SciChart.

What is the Best Chart Library for React?

SciChart is one of the best chart libraries for React. SciChart is used and trusted by all F1 teams, 80% of top banking institutes in the UK and US, and 90% of the world’s leading medical device companies. In fact, 98% of our clients recommended us for complex charting projects across Motorsport, Aerospace and Defence, and Oil and Gas.

We regularly update our software, providing even better performance, new features to enhance your data stories, and more developer support for specific chart types, including demos and examples.

Why SciChart?

  • User-FriendlyIf you live and breathe data, you want to make it work for you, and SciChart makes the data easy to visualize for the end user. Our entire process is beginner-friendly, making us the ideal choice for any developer team. It’s simple—we provide the resources, performance, and features that your developers need to nail the brief on their projects.
  • Extensive APIOur extensive ChartModifier API documentation enables Zooming and Panning behavior, Tooltips, Legends, and much more. This helps you boost interactivity and engagement with the data for your end user, helping them navigate to the answers they’re looking for more easily.
  • Hardware AcceleratedOften people don’t think about performance, but it’s important to consider the potential of having a lot of data, so it’s better to choose a library that’s built for this right away. SciChart is up-to-date, so you can trust the React wrapper. We built this engine ourselves to enable the rendering of millions or even a billion data points in real-time, depending on chart type and hardware configuration.
  • Examples and Documentation (lots of them!)If it’s examples and demos you want, then SciChart has plenty of them (over 100 React examples, in fact). And that’s not to mention the thousands of forums filled with questions from our community and answered by our dedicated team.

Check out the latest React demos and examples available through SciChart in the video below.

We also have helpful articles that troubleshoot common challenges developers face when creating React charts, including what causes React strict mode to double render.

Best Charts for React with SciChart

Popular React chart types supported by SciChart include polar charts, pie charts, candlestick charts, and heatmaps.

Polar charts can be used with different series. It’s easy to switch between a column, line and mountain series. You can also flip the axis and add different column modes. It’s good for creating different combinations of data representations and customizations and parameters.

Versatile applications of polar charts extend to everything from an RPM gauge chart to an analogue clock. You can even create a pie chart using the polar chart, as well as add band charts, stacked column charts or a polar heatmap.

Just like with our WPF and JavaScript chart libraries, you’ll also have access to our real-time performance demo, supporting millions of data points.

How to Create Pie Charts in React JS with SciChart?

As an example of how to create React charts, we’re showcasing how to build a pie chart with React—one of the most popular charts.

We recommend using a library to create a pie chart in React JS for a professional finish. Displaying percentages of a whole, a pie chart is an effective way to visualize the comparison of amounts. This could encompass anything from sales stats for various car brands to the number of votes in an election. The simplicity and versatility of the pie chart make this a popular choice for React data visualizations.

 

With SciChart, you can refer to the React pie chart demo to view the source in GitHub. From there, you can access all the properties you need to finish your chart project with a flourish. Create a component and then view the properties to make the chart all your own.

Everything from styling and theming (with the ability to create a custom theme for your brand) to chart annotations is ready and waiting for developers to work their magic and bring impressive data visualizations to life.

This is a relatively simple chart, but one that is popular for its ease of understanding for stakeholders and end users across any sector. SciChart is working on version four of our hardware-accelerated pie chart to provide an even better experience for our customers.

We could delve further into the various charts available, but we cover this well in our blog on the best React chart examples.

 

Compatible with both JavaScript and TypeScript why not explore the reasons SciChart is considered a world-leading React chart library? We provide high-performance data visualizations, enabling the rendering of millions of data points in real-time, and there’s no lag even on lower-grade hardware. You’ll find our charts applied across data projects and dashboards managed by powerhouses in medtech, healthcare, motorsport, defence and aerospace, and finance and trading. Could your organization be the next to benefit from our innovative React chart support? Get started with a free trial.

We’ve created a set of tutorials on using scichart-react, which you can find here:

By Michael Klishevich | Dec 16, 2024
Michael, an MMath graduate and JavaScript Tech Lead, leverages his mathematical expertise to drive advanced JavaScript solutions at SciChart, enhancing high-performance, data-driven applications.

Leave a Reply