react-native-tool

초간단 파이차트!

RNDK 2023. 6. 28. 11:14
import React, {FC} from 'react';
import styled from 'styled-components/native';

type PieChartProps = {
data: number[];
};

const PieChart: FC<PieChartProps> = ({data}) => {
const total = data.reduce((acc, value) => acc + value, 0);

return (
<Container>
{data.map((value, index) => {
const percentage = (value / total) * 100;
const color = `hsl(${index * 60}, 70%, 50%)`; // 색상을 여러 가지로 구분하기 위해 HSL 컬러 모델을 사용합니다.

return (
<Segment key={index} color={color} percentage={percentage}>
<Label>{percentage.toFixed(1)}%</Label>
</Segment>
);
})}
</Container>
);
};

const Container = styled.View`
flex: 1;
justify-content: center;
align-items: center;
`;

const Segment = styled.View<any>`
width: 200px;
height: 200px;
border-radius: 100px;
border-width: 10px;
border-color: ${props => props.color};
overflow: hidden;
position: absolute;
transform: rotate(${props => props.percentage * 3.6}deg);
`;

const Label = styled.Text`
font-size: 16px;
font-weight: bold;
text-align: center;
`;

export default PieChart;