首页 > 解决方案 > How concatenate string with value in recharts - ReactJS

问题描述

I want to concatenate "%" with the value on barchart when values show on top of the bars.

How to do that ?

 <ResponsiveContainer width="99%" aspect={4}>
      <BarChart data={chartData} margin={{ top: 0, left: -30, right: 0, bottom: 0 }}>
        <Bar dataKey='hum' name="Humidity" barSize={15} fill='rgba(0, 60, 255, 0.6)' unit=" %" >
        <LabelList dataKey="hum" position="top" />
        </Bar>
        <CartesianGrid stroke="#ccc" strokeDasharray="5 5" />
        <XAxis dataKey="date" tick={{ fontSize: 12, fill: 'black' }} tickFormatter={(unixTime) => moment(unixTime).format('DD.MM - HHч.')} interval={1} />
        <YAxis tick={{ fontSize: 12, fill: 'black' }} />
        <Tooltip />
      </BarChart>
 </ResponsiveContainer>

barchart

I return data like this:

formatData = (data) =>
data.map(({ dt_txt, main, pop }) => ({
  // date -> Can be used as dataKey for XAxis
  //Further you can format the date as per your need
  date: dt_txt,
  // temp -> Can be used as dataKey for Line
  temp: main.temp,
  hum: main.humidity,
  rain:  pop
}));

I want to concatenate "%" to hum property and display the values on the chart.

标签: javascriptreactjsrecharts

解决方案


尝试在 YAxis 中赋予“unit”属性,例如 <YAxis tick={{ fontSize: 12, fill: 'black' }} unit="%"/>

编辑:尝试像这样更改 LabelList 标签。

<LabelList dataKey="hum" position="top" content={renderLabel} />

并在您的代码中添加以下功能性反应组件。

const renderLabel= ({value}) => {

  return (
    <span>{ value + '%'}</span>
  );
};

推荐阅读