javascriptreactjsrecharts

How can i create a horizontal scrolling chart in react using rechartjs?


I'd like to create a areachart with Rechart.js but having the y-axis fixed position when i scroll.

Whats happening for me is the data gets crumbled, how could i make it scroll-able, i could'nt able to find in the docs also, Any ideas?

Thank you

  const validate = React.useCallback(() => {
    setArr((prevState) =>
      [...prevState, { X: Math.random() >= 0.5 ? 5 : 0 }]
    );
  }, []);

  React.useEffect(() => {
    if (timeoutRef.current !== null) {
      clearTimeout(timeoutRef.current);
    }
    const interval = 6000;
    const speed = 1000;
    for (let i = 0; i < interval; i++) {
      timeoutRef.current = setTimeout(() => {
        timeoutRef.current = null;
        validate();
      }, i * speed);
    }
  }, [validate]);
  return (
    <div>
      <h1>{time}</h1>
      <AreaChart
        width={730}
        height={250}
        data={arr}
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
      >
        {/* <CartesianGrid strokeDasharray='3 3' /> */}

        <YAxis />
        <XAxis additive='sum' />
        <Tooltip />
        <Legend />
        <Area
          type='monotone'
          dataKey='X'
          stroke='#8884d8'
          isAnimationActive={false}
          additive='sum'
        />
        <Brush startIndex={0} endIndex={10}>
          <AreaChart>
            <Area dataKey='X' isAnimationActive={false} />
          </AreaChart>
        </Brush>
      </AreaChart>
    </div>
  );
}

Solution

  • The solution I found is setting the width of ResponsiveContainer according to your data length and setting its overflow-x: scroll here's an example

    <ResponsiveContainer width={calculateBarchartWidth(data.length)} height{300} className="overflow-x-scroll"> Your inner JSX goes here ...</ResponsiveContainer>

    I'm using Tailwind, you can use whatever you like and here's the method of calculateBarchartWidth

    const calculateBarchartWidth = (numberOfItem = 9) => { if (numberOfItem > 9) return numberOfItem * 100; return '100%'; };