Coder Social home page Coder Social logo

react-gauge-chart's Introduction

react-gauge-chart

React component for displaying a gauge chart, using D3.js

Usage

Install it by running npm install react-gauge-chart. Then to use it:

import GaugeChart from 'react-gauge-chart'

<GaugeChart id="gauge-chart1" />

Examples

Check the demo below for live examples of the charts

To create a default chart

<GaugeChart id="gauge-chart1" />

Chart with 20 levels and pointer at 86%

<GaugeChart id="gauge-chart2" 
  nrOfLevels={20} 
  percent={0.86} 
/>

Chart with custom colors and larger arc width

<GaugeChart id="gauge-chart3" 
  nrOfLevels={30} 
  colors={["#FF5F6D", "#FFC371"]} 
  arcWidth={0.3} 
  percent={0.37} 
/>

Chart with other corner radius and larger padding between arcs

<GaugeChart id="gauge-chart4" 
  nrOfLevels={10} 
  arcPadding={0.1} 
  cornerRadius={3} 
  percent={0.6} 
/>

Chart with custom arcs width

<GaugeChart id="gauge-chart5"
  nrOfLevels={420}
  arcsLength={[0.3, 0.5, 0.2]}
  colors={['#5BE12C', '#F5CD19', '#EA4228']}
  percent={0.37}
  arcPadding={0.02}
/>

Chart with disabled animation

<GaugeChart id="gauge-chart6" 
  animate={false} 
  nrOfLevels={15} 
  percent={0.56} 
  needleColor="#345243" 
/>

Demo

https://martin36.github.io/react-gauge-chart/

API

Warning: Do not use the same id for multiple charts, as it will put multiple charts in the same container

Note: If you do any updates to the props of the chart, it will rerender with a different size (it's a bug). To prevent this set a fixed height for the chart e.g.

const chartStyle = {
  height: 250,
}

<GaugeChart id="gauge-chart1" style={chartStyle} />

The props for the chart:

Name PropType Description Default value
id PropTypes.string.isRequired Used for the identification of the div surrounding the chart
className PropTypes.string Add className to the div container
style PropTypes.object Add style to the div container { width: '100%' }
marginInPercent PropTypes.number Margin for the chart inside the containing SVG element 0.05
cornerRadius PropTypes.number Corner radius for the elements in the chart 6
nrOfLevels PropTypes.number The number of elements displayed in the arc 3
percent PropTypes.number The number where the pointer should point to (between 0 and 1) 0.4
arcPadding PropTypes.number The distance between the elements in the arc 0.05
arcWidth PropTypes.number The thickness of the arc 0.2
colors PropTypes.array An array of colors in HEX format displayed in the arc ["#00FF00", "#FF0000"]
textColor PropTypes.string The color of the text "#FFFFFF"
needleColor PropTypes.string The color of the needle triangle "#464A4F"
needleBaseColor PropTypes.string The color of the circle at the base of the needle "#464A4F"
hideText PropTypes.bool Whether or not to hide the percentage display false
arcsLength PropTypes.array An array specifying the length of each individual arc. If this prop is set, the nrOfLevels prop will have no effect none
animate PropTypes.bool Whether or not to animate the needle when loaded true
animDelay PropTypes.number Delay in ms before starting the needle animation 500
animateDuration PropTypes.number Duration in ms for the needle animation 3000
formatTextValue PropTypes.func Format you own text value (example: value => value+'%') null
textComponent PropTypes.elements Custom text label textComponent null
textComponentContainerClassName PropTypes.string Add className to the text component container
needleScale PropTypes.number Needle arc cornerRadius 0.55
customNeedleComponent PropTypes.element Custom needle component Note: Make sure to rotate the needle as per the percentage value null
customNeedleComponentClassName PropTypes.string Add className to the custom needle container
customNeedleStyle PropsTypes.object Add style to custom needle container div

|

Colors for the chart

The colors could either be specified as an array of hex color values, such as ["#FF0000", "#00FF00", "#0000FF"] where each arc would a color in the array (colors are assigned from left to right). If that is the case, then the length of the array must match the number of levels in the arc. If the number of colors does not match the number of levels, then the first and the last color from the colors array will be selected and the arcs will get colors that are interpolated between those. The interpolation is done using d3.interpolateHsl.

react-gauge-chart's People

Contributors

ariataylor96 avatar bossbele avatar dependabot[bot] avatar dominicboston avatar kashaudhan avatar listennn08 avatar loicevenium avatar manulife-csl avatar martin36 avatar meirkl avatar mkrishnan-codes avatar rahul-rkm avatar rsolomon avatar smchinna avatar stevenhankin avatar thebarda avatar tobiasbueschel avatar yagopajarino 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

react-gauge-chart's Issues

formatting text/label

is it possible to format the text/label by rendering a string? specifically I'm looking to remove the % percentage symbol from the label. thanks!

Labels on arcs

I @Martin36 , I think i can add labels to arcs as an option. Would you be interested by this feature?

Disable animation

I would like to disable the animation with a property like 'animate=false' or something

Gauge re-initialized whenever parent re-renders (needle animates from 0)

I don't know why this is a problem only I appear to be seeing, but when the parent of a GaugeChart component re-renders due to prop changes, the GaugeChart needle resets to 0 and then animates to its current value, causing it to oscillate wildly when there are frequent prop changes. This happens even if the props passed to GaugeChart don't change (the parent renders other components as well). I'm using useMemo to ensure the props to GaugeChart like arcsLength and colors don't change.

I've verified (using an onEffect hook) that the parent is only re-rendering, and not being unmounted and re-mounted.

I did a bit of debugging in the GaugeChart code, and I was able to see that this call to initChart() with no parameters inside the useLayoutEffect hook was being called every time the parent's props changed. The dependencies listed for the useLayoutEffect hook include the whole props object for the GaugeChart component - doesn't that mean that the callback passed to useLayoutEffect will be re-invoked every time the GaugeChart props change?

I was able to stop the behaviour in my application by rolling back to [email protected]. The introduction of the useLayoutEffect hook with props in its dependencies seems to have happened with merge request #74.

Customize Range Value and Text

Gauge reflects a metric from 1-100, but want to have a 'custom' range to show a metric between 50-150%, etc. Can calculate the converted percentage to fit the gauge, but the textLabel shows the conversion

Simpler Request: allow a textValue override to show an custom value/string. If not given, default is the percentage. String to allow both "125%", or "High Risk!" type of information.

More Involved Request: Set a lower/upper range to convert the calculated percentage against (default being 1/100%), so the user doesn't have to calculate the ranges ad hoc.

Thanks!

CSS unexpected token

Simple npm install and attempt to run breaks application returning this message:

`/node_modules/react-gauge-chart/dist/GaugeChart/style.css:1
.percent-text{
^

SyntaxError: Unexpected token .
at Module._compile (internal/modules/cjs/loader.js:721:23)
at Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Object.newLoader [as .js]`

Package can't be used

After installed using yarn, error module not found were shown. This happen both on local environment and a codesandbox environment. Tried troubleshoot by installing d3 (as refer to related issue), still not successful.

This is the codesandbox example that i used. The error can be seen shortly after when the page loaded.

Error on React Native

Hi! I'm trying to use the gauges on a React Native Project but I keep getting the same error. It says that it can't find the file but it's in there. I've verify multiple times. The path is valid.

Can someone help me, please?

Screen Shot 2020-01-24 at 5 59 07 PM

dependency issue with react 18

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@"18.2.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.2 || ^17.0" from [email protected]
npm ERR! node_modules/react-gauge-chart
npm ERR! react-gauge-chart@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/xyz/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/xyz/.npm/_logs/2022-06-25T18_58_01_668Z-debug-0.log

Multiple loading

When the gauge value is updated by componentDidMount method, the gauge chart is loaded several times, that is, multiple gauge charts appear.

TypeError: (0 , _d.arc) is not a function

Hi,
I download the package and install from a local directory using npm install PATH.
The import worked but when I tried to use it I got the following error:

TypeError: (0 , _d.arc) is not a function
GaugeChart
I:/gauge_module/react-gauge-chart/dist/GaugeChart/index.js:54
51 | var container = (0, _react.useRef)({});
52 | var nbArcsToDisplay = (0, _react.useRef)(0);
53 | var colorArray = (0, _react.useRef)([]);

54 | var arcChart = (0, _react.useRef)((0, _d.arc)());
| ^ 55 | var arcData = (0, _react.useRef)([]);
56 | var pieChart = (0, _react.useRef)((0, _d.pie)());
57 | var prevProps = (0, _react.useRef)(props);
View compiled

Changing the text padding/raising the percentage text

hello, I would like to know if is it possible to change text padding through props, what im trying to achieve is supposed to look like this
image

basically lifting it up above the needle.

currently, I only able to change it through dependency files themself by setting the var textPadding = 3; inside index.js but ofcourse it will set back to default after a fresh install, please tell me if I'm missed someway to do it, thanks in advance!

Next.js issue Global CSS cannot be imported from within node_modules.

When installing and using the library in my next.js project, I got this issue:

./node_modules/react-gauge-chart/dist/GaugeChart/style.css
Global CSS cannot be imported from within node_modules.
Read more: https://err.sh/next.js/css-npm
Location: node_modules/react-gauge-chart/dist/GaugeChart/index.js

0.4 release on npm

Hi Martin,

I love this library but I can't find release 0.4 on npm. Do you have plans to push the new release to npm?

onMouseLeave - gauge chart size increases

Hi There,

I am facing an issue with the gauge chart and I am not able to figure out where exactly it is raising from.

I have implemedted a popover component using material-ui and introduced the gauge chart inside the popover modal. On text hover gauge chart is been displayed correctly but during onmouseleave event, the popover component flicks(size of gauge chart) for a tiny second then closes the popover modal. This flicker is currently effecting our UI.

When I test without the gaugechart there is no issue with onmouseleave event. Could anyone please help me where am I going wrong here? Thanks

Reproduced the issue here
https://codesandbox.io/s/react-over-issue-5ibv6?file=/demo.js

Thanks,
:)

Render Stacks Up

whenever there is a change in the states, it draws new gauge below the previous one instead of redrawing the original.

showing min and max range interval

under each corner of the arc can we have the min and max numbers written?

ie: on the left start of it (say 0 degrees) it should state where is the range starting and on the right side (ie 180 degrees) it should say the max amount.

React Hook Warnings

Encountered a few lint warnings;

/Users/stevenhankin/projects/react-gauge-chart/src/lib/GaugeChart/customHooks.js
  19:3  warning  React Hook useEffect has a missing dependency: 'callback'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

/Users/stevenhankin/projects/react-gauge-chart/src/lib/GaugeChart/index.js
  62:6  warning  React Hook useEffect has missing dependencies: 'initChart' and 'props'. Either include them or remove the dependency array                                                                                                            react-hooks/exhaustive-deps
  89:9  warning  The 'handleResize' function makes the dependencies of useEffect Hook (at line 116) change on every render. Move it inside the useEffect callback. Alternatively, wrap the definition of 'handleResize' in its own useCallback() Hook  react-hooks/exhaustive-deps

βœ– 3 problems (0 errors, 3 warnings)

I'll raise a PR for these

Proptypes missing

The proptypes is missing one property. It should be like this:

GaugeChart.propTypes = {
  id: PropTypes.string,
  className: PropTypes.string,
  style: PropTypes.object,
  marginInPercent: PropTypes.number,
  cornerRadius: PropTypes.number,
  nrOfLevels: PropTypes.number,
  percent: PropTypes.number,
  arcPadding: PropTypes.number,
  arcWidth: PropTypes.number,
  arcsLength: PropTypes.array,
  colors: PropTypes.array,
  textColor: PropTypes.string,
  needleColor: PropTypes.string,
  needleBaseColor: PropTypes.string,
  hideText: PropTypes.bool,
  animate: PropTypes.bool,
  formatTextValue: PropTypes.func,
  fontSize: PropTypes.string,
  animateDuration: PropTypes.number,
  animDelay: PropTypes.number,
};

And in the readme needs to be updated to this:
The props for the chart:

Name PropType Description Default value
id PropTypes.string.isRequired Used for the identification of the div surrounding the chart
className PropTypes.string Add className to the div container
style PropTypes.object Add style to the div container { width: '100%' }
marginInPercent PropTypes.number Margin for the chart inside the containing SVG element 0.05
cornerRadius PropTypes.number Corner radius for the elements in the chart 6
nrOfLevels PropTypes.number The number of elements displayed in the arc 3
percent PropTypes.number The number where the pointer should point to (between 0 and 1) 0.4
arcPadding PropTypes.number The distance between the elements in the arc 0.05
arcWidth PropTypes.number The thickness of the arc 0.2
colors PropTypes.array An array of colors in HEX format displayed in the arc ["#00FF00", "#FF0000"]
textColor PropTypes.string The color of the text "#FFFFFF"
needleColor PropTypes.string The color of the needle triangle "#464A4F"
needleBaseColor PropTypes.string The color of the circle at the base of the needle "#464A4F"
hideText PropTypes.bool Whether or not to hide the percentage display false
arcsLength PropTypes.array An array specifying the length of each individual arc. If this prop is set, the nrOfLevels prop will have no effect none
animate PropTypes.bool Whether or not to animate the needle when loaded true
animDelay PropTypes.number Delay in ms before starting the needle animation 500
animateDuration PropTypes.number Duration in ms for the needle animation 3000
formatTextValue PropTypes.func Format you own text value (example: value => value+'%') null

Should i open a PR for this?

Dependencies memory heap

Hello there! What a nice library!

Do you know if there is an option to lighten the dependencies during production build? Our 256Mb machine exploses just once I add the d3 as a direct dependency for this lib.

Are there any workarounds for d3 production builds that could reduce the global heap?

Is it possible to reduce d3 dependency for this library?

Thanks

text position

can i customize text position in bottom of the needle ?

Gauge is hidden when the DIV is 'display:block'

When a DIV's display property is dynamic ('block' or 'none') Gauge is hidden when the DIV is display: block;
When the DIV is display: block, I need the gauge-chart component inside it not to be hidden.

upgrade react peer dependency to version 17

Currently there is a peer dependency on React 16. Are there any plans to upgrade to React 17?

FYI I cloned the repo and ran npm-check-updates -u. As far as I can tell everything worked OK but I only have one chart in my app so that's not a full test

custom needle

image
it will be great if we could change the needle to a different component

d3 dependency

Hey thanks the component looks good. I am concerned about unecessary bloat though since you import * from d3: https://github.com/Martin36/react-gauge-chart/blob/master/src/lib/GaugeChart/index.js

Instead you should import the things you need i.e. import { arc, pie } from 'd3'

Also I see you're using create-react-app which isn't suitable for component libraries. Imo d3 should be listed in externals of the webpack config for example and listed as a peerDependency in package.json.

Or else you could compile a CJS and ESM version with packa.json module entry pinting at the ESM version and most users could import the ESM version so that d3 is properly tree-shaken without that measure ^^

Cannot Use

Should I install d3 as dev dependency? or should I install it alongside this module?

Needle shows current value before animating to it from 0

Hello,

I've got a gauge chart setup like this:

const chartStyle = {
      height: 112.5,
}

return <div style={{width: "250px"}}>
        <GaugeChart
            style={chartStyle}
            nrOfLevels={3}
            arcsLength={arcLengths}
            colors={colours}
            hideText={true}
            percent={gaugePerc}
            arcPadding={0.05}
            cornerRadius={1}
        />
</div>

The value changes from 0, to another value for example 0.7 after an API call returns some data.
I'm seeing an issue where when the gauge changes to another value, the chart does not animate to it at first (it just jumps straight there), before then animating from 0 to it.

See GIF of the issue

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.