Languages
[Edit]
EN

React - own animated bar chart

12 points
Created by:
Lilly-Grace-Greig
571

In this short article we would like to show how to make in React animated bar chart using div elements.

Custom animated bar chart in React.
Custom animated bar chart in React.

Quick solution:

// ONLINE-RUNNER:browser;

// import React from 'react';
// import ReactDOM from 'react-dom';

// ---------------------------------

const containerStyle = {
  	padding: '0 1px',
  	background: '#ffffff',
  	flex: '1'
};

const spaceStyle = {
  	background: '#ffffff',
  	transition: '0.3s'
};

const barStyle = {
  	background: '#00cc00',
  	transition: '0.3s'
};

const Bar = ({value}) => {
  	return (
      <div style={containerStyle}>
        <div style={{...spaceStyle, height: `${100 - value}%`}} />
        <div style={{...barStyle, height: `${value}%`}} />
      </div>
    );
};

const chartStyle = {
  	width: '400px',
  	height: '200px',
	display: 'flex',
  	overflow: 'hidden'
};

const Chart = ({data}) => {
	return (
      <div style={chartStyle}>
        {data.map((value, index) => <Bar key={index} value={value} />)}
      </div>
    );
};

// ---------------------------------

const calculateData = (xOffset) => {
	const data = [ ];
    for (var x = 0; x < 3.1415; x += 0.1) {
        const y = Math.cos(x + xOffset) + 1;
        data.push(50 * y);
    }
  	return data;
};

const App = () => {
    const [data, setData] = React.useState(() => calculateData(0));
  	const xOffsets = [0, 0.7853, 1.5707, 2.3559, 3.1415];
    return (
      <div>
        <Chart data={data} />
        <br />
        <div>
          <span>xOffset: </span>
          {xOffsets.map(xOffset => {
              const handleClick = () => setData(calculateData(xOffset));
              return (
                <button key={xOffset} onClick={handleClick}>{xOffset}</button>
              );
          })}
        </div>
      </div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - animated bar chart
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join