React Native segmented circular progress bar

360 Views Asked by At

I am trying to create a Segmented Circular progress bar (where each segment can have its own size) by using the 'react-native-svg'

enter image description here

here is my code:

const SMCircle = ({ segments }) => {
    const radius = 100;
    const strokeWidth = 20;
    const gap = 10;
    const totalValue = segments.reduce((total, segment) => total + segment.value, 0);
    const circumference = 2 * Math.PI * radius;


    let dashOffset = 0;
    const circleSegments = segments.map((segment, index) => {
        const dashArray = [
          (segment.value / totalValue) * circumference, gap
        ];
        
        const circle = (
          <Circle
            key={index}
            cx={radius}
            cy={radius}
            r={radius - strokeWidth / 2}
            stroke={segment.color}
            strokeWidth={strokeWidth}
            fill="transparent"
            strokeDasharray={dashArray.join(',')}
            strokeDashoffset={dashOffset}
          />
        );
        
        dashOffset += dashArray[0] + dashArray[1]; // Increment dashOffset
        return circle;
      });
return (
      <View>
        <Svg height={2 * radius} width={2 * radius}>
          {circleSegments}
        </Svg>
      </View>
    );
  };
  

  export default SMCircle;


In App.js I am using the component and following data

const segments = [
    { value: 25, color: 'red' },
    { value: 15, color: 'blue' },
    { value: 30, color: 'green' },
    { value: 10, color: 'yellow' },
    { value: 20, color: 'purple' },
  ];

<SMCircle segments={segments} />

and here is out put not sure why purple is repeating multiple times and other segments are not appearing.

enter image description here

I have used 'react-native-svg', could not find any othee similar package that I can use in React Native.

0

There are 0 best solutions below