PL
React - własny animowany wykres słupkowy
3 points
W tym krótkim artykule chcielibyśmy pokazać, jak stworzyć animowany wykres słupkowy w Reakcie przy użyciu elementów div.

Szybkie rozwiązanie:
xxxxxxxxxx
1
// import React from 'react';
2
// import ReactDOM from 'react-dom';
3
4
// ---------------------------------
5
6
const containerStyle = {
7
padding: '0 1px',
8
background: '#ffffff',
9
flex: '1'
10
};
11
12
const spaceStyle = {
13
background: '#ffffff',
14
transition: '0.3s'
15
};
16
17
const barStyle = {
18
background: '#00cc00',
19
transition: '0.3s'
20
};
21
22
const Bar = ({value}) => {
23
return (
24
<div style={containerStyle}>
25
<div style={{spaceStyle, height: `${100 - value}%`}} />
26
<div style={{barStyle, height: `${value}%`}} />
27
</div>
28
);
29
};
30
31
const chartStyle = {
32
width: '400px',
33
height: '300px',
34
display: 'flex',
35
overflow: 'hidden'
36
};
37
38
const Chart = ({data}) => {
39
return (
40
<div style={chartStyle}>
41
{data.map((value, index) => <Bar key={index} value={value} />)}
42
</div>
43
);
44
};
45
46
// ---------------------------------
47
48
const calculateData = (xOffset) => {
49
const data = [ ];
50
for (var x = 0; x < 3.1415; x += 0.1) {
51
const y = Math.cos(x + xOffset) + 1;
52
data.push(50 * y);
53
}
54
return data;
55
};
56
57
const App = () => {
58
const [data, setData] = React.useState(() => calculateData(0));
59
const xOffsets = [0, 0.7853, 1.5707, 2.3559, 3.1415];
60
return (
61
<div>
62
<Chart data={data} />
63
<br />
64
<div>
65
<span>xOffset: </span>
66
{xOffsets.map(xOffset => {
67
const handleClick = () => setData(calculateData(xOffset));
68
return (
69
<button key={xOffset} onClick={handleClick}>{xOffset}</button>
70
);
71
})}
72
</div>
73
</div>
74
);
75
};
76
77
const root = document.querySelector('#root');
78
ReactDOM.render(<App />, root);