Skip to content

Applying CSS to chart components

Dimitris - Rafail Katsampas edited this page Oct 23, 2020 · 4 revisions

As a matter of fact, ui-chart plugin renders charts onto a CanvasView. Any additional components are simply drawn on it. As a view, chart can be styled in terms of background color and dimensions, but this may be limiting when it comes to styling things like axis, labels, and legends using CSS.

Fortunately, we have a solution for you. This block of code is an example of setting styling programmatically.

main-page.ts

export function onLineChartLoaded(args) {
    const chart = args.object as LineChart;
    chart.getXAxis().setTextColor('red');

    const data = new Array(500).fill(0).map((v, i) => ({
        index: i,
        value: Math.random() * 1,
    }));

    const sets = [];
    const set = new LineDataSet(data, 'Legend Label', 'index', 'value');
    set.setColor('blue');
    sets.push(set);

    // Create a data object with the data sets
    const ld = new LineData(sets);

    // Set data
    chart.setData(ld);
}

But what do I do if I want to develop a certain CSS theme? Thanks to NativeScript, there is an alternative to make use of CSS styling even if certain components can't be directly styled. We'll style the code I posted earlier using method 'getCssVariable' from Style class.

First of all, we declare CSS variables to chart style scope.

main-page.css

#line-chart {
    --axis-text-color: red;
    --data-set-color: blue;
}

Then, we get the values of those variables programmatically.

main-page.ts

export function onLineChartLoaded(args) {
    const chart = args.object as LineChart;
    chart.getXAxis().setTextColor(chart.style.getCssVariable('--axis-text-color'));

    const data = new Array(500).fill(0).map((v, i) => ({
        index: i,
        value: Math.random() * 1,
    }));

    const sets = [];
    const set = new LineDataSet(data, 'Legend Label', 'index', 'value');
    set.setColor(chart.style.getCssVariable('--data-set-color'));
    sets.push(set);

    // Create a data object with the data sets
    const ld = new LineData(sets);

    // Set data
    chart.setData(ld);
}

And that's it. You just styled non-view components on ui-chart using CSS variables.

Clone this wiki locally