Youssef Lotfi
Youssef Lotfi

Reputation: 43

How to create a horizontal Bar Componenent with Chart.js

I want to create Horizontal Bar chart Component , I've Add type : "horizontalBar", but it still Vertical Bar chart.

i;m using chartjs library. This is my chart Component

import { Bar } from "react-chartjs-2";

class Chart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      type: "horizontalBar",
      chartData: {
        labels: ["Casa", "Marrakesh", "Agadir", "tanger", "rabat"],
        datasets: [
          {
            label: "Population",
            data: [602000, 601000, 600200, 602500, 600300],
            backgroundColor: ["red", "green", "blue", "black", "purple"],
          },
        ],
      },
    };
  }
  render() {
    return (
      <div>
        <Bar
          data={this.state.chartData}
          width={100}
          height={50}
          options={{}}
          type={"horizontalBar"}
        />
      </div>
    );
  }
}
export default Chart;

this is App component :

import "./App.css";
import Chart from "./components/Charts";

function App() {
  return (
    <div className="App">
      <Chart />
    </div>
  );
}

export default App;

and thank you so much.

Upvotes: 1

Views: 2723

Answers (1)

codingwithmanny
codingwithmanny

Reputation: 1184

I believe you need to use the HorizontalBar import instead.

import React from 'react';
import {HorizontalBar} from 'react-chartjs-2';

const data = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
  datasets: [
    {
      label: 'My First dataset',
      backgroundColor: 'rgba(255,99,132,0.2)',
      borderColor: 'rgba(255,99,132,1)',
      borderWidth: 1,
      hoverBackgroundColor: 'rgba(255,99,132,0.4)',
      hoverBorderColor: 'rgba(255,99,132,1)',
      data: [65, 59, 80, 81, 56, 55, 40]
    }
  ]
};

export default React.createClass({
  displayName: 'BarExample',

  render() {
    return (
      <div>
        <h2>Horizontal Bar Example</h2>
        <HorizontalBar data={data} />
      </div>
    );
  }
});

Reference: https://github.com/reactchartjs/react-chartjs-2/blob/52d6c3e307778893a7f641b0bf540cf336bd85b4/example/src/charts/HorizontalBar.js

Upvotes: 2

Related Questions