Coder Social home page Coder Social logo

kevinsqi / react-circular-progressbar Goto Github PK

View Code? Open in Web Editor NEW
1.1K 9.0 129.0 3.61 MB

A circular progressbar component, built with SVG and extensively customizable

Home Page: http://www.kevinqi.com/react-circular-progressbar

License: MIT License

CSS 6.27% TypeScript 91.59% JavaScript 2.14%
react svg progressbar

react-circular-progressbar's Introduction

React Circular Progressbar

npm version Build Status Bundle size

A circular progressbar component, built with SVG and extensively customizable. Try it out on CodeSandbox.

animated progressbar progressbar examples

Version 2.0.0 is out! ๐Ÿ‘‹

New features:

Breaking changes: if you're upgrading from an older version, take a look at UPGRADING.md for instructions on how to migrate.

Documentation for v1.x.x will still be available at README_v1.md.

Installation

Install with yarn:

yarn add react-circular-progressbar

or npm:

npm install --save react-circular-progressbar

Usage

Import the component and default styles:

import { CircularProgressbar } from 'react-circular-progressbar';
import 'react-circular-progressbar/dist/styles.css';

Note: Importing CSS requires a CSS loader (if you're using create-react-app, this is already set up for you). If you don't have a CSS loader, you can copy styles.css into your project instead.

Now you can use the component:

const percentage = 66;

<CircularProgressbar value={percentage} text={`${percentage}%`} />;

If your values are not in percentages, you can adjust minValue and maxValue to select the scale you want:

const value = 0.66;

<CircularProgressbar value={value} maxValue={1} text={`${value * 100}%`} />;

The progressbar is designed to fill the width of its container. You can size the progressbar by sizing its container:

<div style={{ width: 200, height: 200 }}>
  <CircularProgressbar value={66} />
</div>

This makes the progressbar work well with responsive designs and grid systems.

Props

Take a look at the CodeSandbox for interactive examples on how to use these props.

โ„น๏ธ Version 1.0.0 removed the classForPercentage and textForPercentage props in favor of className and text props. Version 2.0.0 replaces percentage with value and removes the initialAnimation prop. Take a look at UPGRADING.md for instructions on how to migrate.

Name Description
value Completion value of the progressbar, from minValue to maxValue. Required.
minValue Minimum value of the progressbar. Default: 0.
maxValue Maximum value of the progressbar. Default: 100.
className Classes to apply to the svg element. Default: ''.
text Text to display inside progressbar. Default: ''.
strokeWidth Width of circular line relative to total width of component, a value from 0-100. Default: 8.
background Whether to display background color. Default: false.
backgroundPadding Padding between background circle and path/trail relative to total width of component. Only used if background is true. Default: 0.
counterClockwise Whether to rotate progressbar in counterclockwise direction. Default: false.
circleRatio Number from 0-1 representing ratio of the full circle diameter the progressbar should use. Default: 1.
classes Object allowing overrides of classNames of each svg subcomponent (root, trail, path, text, background). Enables styling with react-jss. See this PR for more detail.
styles Object allowing customization of styles of each svg subcomponent (root, trail, path, text, background).

Theming (customizing styles)

Use CSS or inline styles to customize the styling - the default CSS is a good starting point, but you can override it as needed.

Using the styles prop

You can use the styles prop to customize each part of the progressbar (the root svg, path, trail, text, and background). This uses the native style prop for each subcomponent, so you can use any CSS properties here, not just the ones mentioned below.

As a convenience, you can use buildStyles to configure the most common style changes:

import { CircularProgressbar, buildStyles } from 'react-circular-progressbar';

const percentage = 66;

<CircularProgressbar
  value={percentage}
  text={`${percentage}%`}
  styles={buildStyles({
    // Rotation of path and trail, in number of turns (0-1)
    rotation: 0.25,

    // Whether to use rounded or flat corners on the ends - can use 'butt' or 'round'
    strokeLinecap: 'butt',

    // Text size
    textSize: '16px',

    // How long animation takes to go from one percentage to another, in seconds
    pathTransitionDuration: 0.5,

    // Can specify path transition in more detail, or remove it entirely
    // pathTransition: 'none',

    // Colors
    pathColor: `rgba(62, 152, 199, ${percentage / 100})`,
    textColor: '#f88',
    trailColor: '#d6d6d6',
    backgroundColor: '#3e98c7',
  })}
/>;

buildStyles is a shorthand, but you can also build the styles object yourself. It's an object with root, path, trail, text, and background properties, which are each a set of inline styles to apply to the relevant SVG subcomponent. Here's the equivalent set of styles as above, without using buildStyles:

<CircularProgressbar
  value={percentage}
  text={`${percentage}%`}
  styles={{
    // Customize the root svg element
    root: {},
    // Customize the path, i.e. the "completed progress"
    path: {
      // Path color
      stroke: `rgba(62, 152, 199, ${percentage / 100})`,
      // Whether to use rounded or flat corners on the ends - can use 'butt' or 'round'
      strokeLinecap: 'butt',
      // Customize transition animation
      transition: 'stroke-dashoffset 0.5s ease 0s',
      // Rotate the path
      transform: 'rotate(0.25turn)',
      transformOrigin: 'center center',
    },
    // Customize the circle behind the path, i.e. the "total progress"
    trail: {
      // Trail color
      stroke: '#d6d6d6',
      // Whether to use rounded or flat corners on the ends - can use 'butt' or 'round'
      strokeLinecap: 'butt',
      // Rotate the trail
      transform: 'rotate(0.25turn)',
      transformOrigin: 'center center',
    },
    // Customize the text
    text: {
      // Text color
      fill: '#f88',
      // Text size
      fontSize: '16px',
    },
    // Customize background - only used when the `background` prop is true
    background: {
      fill: '#3e98c7',
    },
  }}
/>

However, you're not limited to the CSS properties shown aboveโ€”you have the full set of SVG CSS properties available to you when you use prop.styles.

See the CodeSandbox examples for a live example on how to customize styles.

Using CSS

You can also customize styles with CSS. There are equivalent CSS hooks for the root, path, trail, text, and background of the progressbar.

If you're importing the default styles, you can override the defaults like this:

import 'react-circular-progressbar/dist/styles.css';
import './custom.css';
// custom.css
.CircularProgressbar-path {
  stroke: red;
}
.CircularProgressbar-trail {
  stroke: gray;
}
.CircularProgressbar-text {
  fill: yellow;
}
.CircularProgressbar-background {
  fill: green;
}

Adding arbitrary text or content inside the progressbar

If you want to add multiple lines of text or images within the progressbar, you can overlay it on top of a regular <CircularProgressbar /> using absolute positioning. react-circular-progressbar ships with a CircularProgressbarWithChildren component which makes it easy to do that by using JSX children:

import { CircularProgressbarWithChildren } from 'react-circular-progressbar';

<CircularProgressbarWithChildren value={66}>
  {/* Put any JSX content in here that you'd like. It'll be vertically and horizonally centered. */}
  <img style={{ width: 40, marginTop: -5 }} src="https://i.imgur.com/b9NyUGm.png" alt="doge" />
  <div style={{ fontSize: 12, marginTop: -5 }}>
    <strong>66%</strong> mate
  </div>
</CircularProgressbarWithChildren>;

CircularProgressbarWithChildren example

CircularProgressbarWithChildren has all the same props as CircularProgressbar - you can use it the exact same way otherwise.

Animating text

If you want to animate the text as well as the path, you'll need to transition the value prop from one value to another using a third-party animation library like react-move and an easing library like d3-ease.

You can use a render prop wrapper like AnimatedProgressProvider.js inside this Codesandbox to help manage the transitioning value, and use it like this:

import { easeQuadInOut } from 'd3-ease';

<AnimatedProgressProvider
  valueStart={0}
  valueEnd={66}
  duration={1.4}
  easingFunction={easeQuadInOut}
>
  {(value) => {
    const roundedValue = Math.round(value);
    return (
      <CircularProgressbar
        value={value}
        text={`${roundedValue}%`}
        /* This is important to include, because if you're fully managing the
        animation yourself, you'll want to disable the CSS animation. */
        styles={buildStyles({ pathTransition: 'none' })}
      />
    );
  }}
</AnimatedProgressProvider>;

Animating progressbar upon component mount or upon visible

Upon component mount

In order to trigger the default CSS animation on mount, you'll need to change props.value from 0 to your desired value with a setTimeout in componentDidMount. You can use a wrapper component to help manage this like ProgressProvider.js in this Codesandbox. Then you can do:

<ProgressProvider valueStart={0} valueEnd={66}>
  {(value) => <CircularProgressbar value={value} />}
</ProgressProvider>

Upon visible

To animate the progressbar only when it becomes visible (e.g. if it's below the fold), you can use something like react-visibility-sensor which detects whether the component is visible or not. Here's a Codesandbox example.

Fixing text centering in Internet Explorer (IE)

Because the dominant-baseline CSS property does not work in IE, the text may not be centered in IE.

The recommended way to fix this is to instead of using props.text, use CircularProgressbarWithChildren and put your text in props.children, as described here.

However, you can also work around this by setting the text prop to be a <tspan> element and then adjusting the dy vertical offset, like so:

// Use feature or browser detection to determine if IE
const needDominantBaselineFix = ...

<CircularProgressbar
  value={percentage}
  text={<tspan dy={needDominantBaselineFix ? -10 : 0}>{percentage}</tspan>}
/>

See this Codesandbox example to see this in action.

Advanced usage

Supported platforms

react-circular-progressbar does not work with React Native, because React Native does not support <svg> out of the box.

Contributing

Take a look at CONTRIBUTING.md to see how to help contribute to react-circular-progressbar.

License

MIT

react-circular-progressbar's People

Contributors

altanaldeniz avatar antoniogiordano avatar dependabot[bot] avatar ethanae avatar jedwards1211 avatar jeremywho avatar kevinsqi avatar slaweet avatar soroushchehresa avatar sureshinde avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-circular-progressbar's Issues

Fix development/test warnings

when running tests:

Warning: ReactTestUtils has been moved to react-dom/test-utils. Update references to remove this warning.
Warning: Shallow renderer has been moved to react-test-renderer/shallow. Update references to remove this warning.

add direction and starting point props

Hello,

is it possible to add a counterClockWise boolean prop and a prop for starting point.
I would love the circle go around like so: right (0%), up (25%), left (50%), bottom (75%), right (100%).

Perhaps, this is controllable from css ?

Circular Progressbar Text color is not setting properly

I'm attempting to set the color to #606A7B via CSS, like this:

.CircularProgressbar .CircularProgressbar-text {
	color: '#606A7B';
}

When I inspect the element, I see that it has the proper color set, nothing is overriding it, but in the browser, the text is still black. Am I doing something wrong?

Remove 'Unwind' Animation

I am using this component to make a timer component and was wondering how I could go about removing the 'unwind' animation after I reset the percentage to 0.

Right now, once the timer runs out the progressbar follows back around the circle the way it came. I want to have the progressbar just remove it's progress and start how it began. Any ideas?

Feature request: initialAnimation speed/delay

Hello!

I would like to run the initialAnimation when my component is already mounted and also I would like to change the animation speed. Is that currently possible? I could do a pull request if you are interested in this. :-)

Thank you.

Vertical align of percentage text in IE 10 +

So IE doesn't support dominant-baseline/alignment-baseline: central/middle css properties.
How do you suggest to vertical align the precentage text inside the circle?
(In IE 10 it's aligned to the top)

Text Alignment

reactcircleissue

The progressbar appears to have the text not aligned in the center. Is that supposed to be its alignment or how am I using it incorrectly.

<CircularProgressbar className="progress-bar" percentage={95} styles={{path: {stroke: 'black'}}}/>`

Unrounded Progress Container

This looks great, I am about to drop it in but is it possible to style the progress element to have "hard edges"? The style of our site is boxy and nothing has border-radius soft looking styles. Thanks! I am looking for a style like this from react-progress-circle:
screen shot 2018-03-02 at 9 28 37 am

I don't want to use the react-progress-circle component because it isn't as flexible in other areas. Thanks!

Make the component resizable

Right now the component is scaled down to fit the container, but the viewbox is always 100x100px. During scaling down the interface is rendered with approximation and the progress bar is not sharp as a full resolution render. It would be very useful to actually pass the size as parameter and calculate based on that.

Failed prop type: Calling PropTypes validators directly is not supported

When using

<CircularProgressbar percentage={domain.attributes.overview.top_three} strokeWidth={16} />

I am getting the following warning
warning.js:36 Warning: Failed prop type: Calling PropTypes validators directly is not supported by the prop-types package. Use PropTypes.checkPropTypes() to call them.

How to set ending point

Hello,
How if we want to set the end point? currently only set to 100, I want to set the end point to 10.

thanks, great component.

Display circle

Hi @iqnivek !

I tried using this component in this manner:

However, currently when I run it, only the percentage (eg. 60.2%) is displayed, but not the circle itself. What am I doing wrong..?

Is it possible to bind "percentage" to a timer component?

Hello, I'm attempting to dynamically bind the "percentage" value to a timer component. I am able to get the progress circle percentage to update with a certain function, but I am unable to include that function in ComponentDidUpdate()...it causes an infinite loop. So, right now, the progress circle updates whenever my function is called, but I am unable to animate the percentage dynamically. Any suggestions?

Thanks,
Carlos

Display text on multiple lines

I was trying to customise the "textForPercentage" function and pass it a newline (<br/>) tag but html tags get removed.
Is there an easy way to keep the percentages displayed (and animated) and just display a text below the percentage?
Like in this picture
screencap

This is how I tried to call textForPercentage:

textForPercentage={(p) => { return `${p}%<br/>sold` }}

If html is not desired, maybe just support the "\n" newline character and replace it with a <br/> on display?
So

textForPercentage={(p) => { return `${p}%\nsold` }}

would also be a valid option

Radius

nice component , great work.

anyway , how to change radius circular progress, expected to simply change radius

<CircularProgressbar percentage={this.state.value1} radius={25} />

thanks

Inline styling for display of circle

@iqnivek , I think I am starting to get the gist of inline styling, but here is my current question... How do I differentiate between the styling for bar itself, path, trail, and text?

For example, I currently use:

const styles = {

circularProgressLg: {
paddingLeft: 40,
paddingRight: 40,
paddingBottom: 10,
width: "50%",
stroke: "#3e98c7",
strokeLinecap: "round",
transition: "stroke-dashoffset 0.5s ease 0s",
}

};

And then use this to display:

     <div style={styles.circularProgressLg} className="col-lg-6 col-lg-offset-3 col-md-offset-3 col-md-6  col-sm-offset-2 col-sm-8 col-xs-12">
          <CircularProgressbar percentage={60.2} initialAnimation={true} />
        </div>

But how do I include the other properties for path, trail, and text?

Also, I currently include "width" in the same set as the path properties instead of separately. Is there a difference?

Thanks!

`styles.root` is not applied

The code states that there is a property for applying CSS styling to the root node, but it's unused in the actual rendering. Could this be fixed?

Not working showing just simple text

Just rendering simple text

import React from 'react';

import CircularProgressbar from 'react-circular-progressbar';

class ProgressChart extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      progress: 60,
    };
  }
  render() {
    return (
      <CircularProgressbar percentage={this.state.progress} />
    );
  }
}

export default ProgressChart;

Included style in index.html

<link rel="stylesheet" type="text/css" href="https://raw.githubusercontent.com/iqnivek/react-circular-progressbar/master/src/styles.css">

what am I doing wrong?

screen shot 2017-09-21 at 12 39 26 pm

Display circle using inline styling

Ok, I added this into my .jsx file:

const styles = {
"CircularProgressbar": {
"width": "100%"
},
"CircularProgressbar__CircularProgressbar_path": {
"stroke": "#3e98c7",
"strokeLinecap": "round",
"transition": "stroke-dashoffset 0.5s ease 0s"
},
"CircularProgressbar__CircularProgressbar_trail": {
"stroke": "#d6d6d6"
},
"CircularProgressbar__CircularProgressbar_text": {
"fill": "#3e98c7",
"fontSize": "20px",
"dominantBaseline": "middle",
"textAnchor": "middle"
}
}

But it is currently still not displaying the circle. Any idea what it might be?

Thanks!

@iqnivek

Not working with React 15.5

I get this error With React 15.5.4 and React-dom 15.5.4:
Warning: Failed prop type: Calling PropTypes validators directly is not supported by the 'prop-types' package. Use PropTypes.checkPropTypes() to call them.

Looks like react-circular-progressbar needs to use the prop-types library.
Don't Call PropTypes Warning

Progress animation and display

I currently have two problems with the circular progress path:

  1. It is displaying as a full circle no matter what percentage is set. For example, with this:

     <CircularProgressbar percentage={60.2} initialAnimation={true}/>
    

A full circle is displayed rather than just 60.2% even though the text does display as 60.2%.

  1. There is no initial animation on refresh even though it is set to true.

Can you advise, @iqnivek ?

Thanks.

Feature request: way to render without <text>

I could hide the text by rendering with textForPercentage={() => ''}, but it would be cleaner if I could prevent it from rendering any <text> at all.

It could avoid rendering <text> if textForPercentage={null} or if it returns something falsy.

Personally I think having a textForPercentage function is more complicated than necessary; since one is always passing in the percentage, one could easily just pass in text={`${percentage}%`} as well if this lib supported it. Same goes for classForProperty.

Note: react-bootstrap progress bars, which don't show any text by default, can be passed text to display as children.

Is there a way to nest progressbars?

I apologize if this is a non conventional way of asking this question, but I really like what you've done and I'm trying to nest one progressbar within the other. Does this functionality exist, and if so could you prompt me on how to do so?

If this functionality doesn't exist it would be a great feature to build out.

Thx.

How to create a countdown timer

Hey,

firstly thanks for good plugin and nice work!

I have some idea which you can try to consider is ok.
In you plugin you base on the percentage and max value expressed by the 100%. For stuff which is based on the percent is ok. But I faced with following problem, I needed to run a circular progress based on the n-seconds, that's mean I need to countdown (increments/decrements). Max value is 5 and need to countdown to 0 (increments should be possible too, passed as an option).

I don't know is that idea will be good for you, but changes shouldn't be hard I guess.

Time for the animation

Hi,
I wanted to know if there was any way of changing the time of the animation, example from 0% to 80% and make it faster or slower.
I tried changing

ChangingProgressbar.defaultProps = {
  interval: 1000
};

the value of the interval variable, but it does not have any effect on the duration of the animation.
Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.