I am trying to learn a data viz library, Victory. But my question is still fundamentally about JS + React.
I am building a bar chart that when clicked triggers an alert message.
I’m sure there is an easier way to build this but I am trying to use a specific methodology as part of a coding follow-along.
So this is my code:
import React, { Component } from "react";
import { VictoryBar } from "victory";
import Bar from "./bar";
class VicSimpleEvent extends Component {
constructor() {
super();
this.state = {};
}
render() {
return (
<div>
<p>Simple Events</p>
<VictoryBar
data={[
{ x: 1, y: 2 },
{ x: 2, y: 4 },
{ x: 3, y: 7 },
{ x: 4, y: 3 },
{ x: 5, y: 5 }
]}
dataComponent={
<Bar
events={
{
// // onClick: evt => alert(`(${evt.clientX}, ${evt.clientY})`)
// // onClick: () => alert("hey!")
// handleOnClick: () => alert("hey!")
}
}
/>
}
/>
</div>
);
}
}
export default VicSimpleEvent;
And:
import React from "react";
const Bar = props => {
console.log(props);
const { id, x, y, style, data } = props;
return (
<svg width="450" height="300">
<g className="bar">
{data.map(each => (
<rect
// key={id}
x={x}
y={y}
width="55"
height="300"
style={{ style }}
/>
))}
</g>
</svg>
);
};
export default Bar;
My questions are:
- How do I get the alert to run when each bar is clicked? As you can see from my commented out code, I was trying different things. just to understand what the interactions were.
- When I try to create a unique key for each item rendered in the child component, I first used
index
thenkey
- both of which are sent in viaprops
. However, neither were successful and that is because - I think - theprops
are being sent in 5 times so there are 5 instances of the sameindex
orkey
. You can see from console log thatprops
are being sent 5 times. But I am confused where/how this is happening?
Any help would be appreciated!