I added a plotly component to my project following this guide. When the user clicks on the bar chart, I need to get the data corresponding to the bar that the user clicked on. The structure is just like in the guide I followed and everything works great, I just do not know how to add a click event to the bar chart.
The bar chart looks like this
When the user clicks the chart, I need to get the associated vehicle make, like "HUMMER" for example.
Add a comment
|
2 Answers
After calling Plotly.newPlot, you can add a click event handler and access the clicked data like this
(document.getElementById('myPlotlyDiv') as any).on('plotly_click', function(data){
// The label of the horizontal bar chart
console.log(data.points[0].y);
// The value for the clicked bar
console.log(data.points[0].x);
});
1 Comment
Stack Underflow
Updated answer to ignore the typescript error
Property 'on' does not exist on type "'myPlotlyDiv'", which I found at this SO questionThe guide uses any type. However, your ESLint setup might give you some errors later on:
@typescript-eslint/no-unsafe-member-access: Unsafe member access .on on an `any` value.
@typescript-eslint/no-unsafe-call: Unsafe call of an `any` typed value.
Our days Plotly.js is definitely typed. So, you need to install as a developer dependence some types for plotly.js (e.g. npm i -D @types/plotly.js-dist-min) and use them:
import { PlotlyHTMLElement } from 'plotly.js-dist-min';
const myPlot = document.getElementById('myPlotlyDiv') as PlotlyHTMLElement;
myPlot.on('plotly_click', function(data){
// The label of the horizontal bar chart
console.log(data.points[0].y);
// The value for the clicked bar
console.log(data.points[0].x);
});
});