1

I have a codepen here - https://codepen.io/anon/pen/ddPMVx?editors=1010

It's a simple stacked bar chart

Each stack from the data is in its own layer with a class of 'layer'

I'd like to added another class that is the name of the key from the keys that create the stack

.classed('layer', true)

// .classed((i)=>{
//     return keys[i],
// }, true)
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
ttmt
  • 5,822
  • 27
  • 106
  • 158

2 Answers2

1

You cannot use a function with classed. For further information, have a look at my answer here.

You can use a getter to get the existing classes and add the one you want. However, pay attention to this: the fact that you use the letter i in the argument...

function(i){...

... doesn't mean that it is the index. The index is the second argument, no matter its name. So, it should be:

function(_, i){...

All that being said, this is a way to add the key name without overriding the existing classes:

.attr("class", function(_, i){
    return d3.select(this).attr("class") + " " + keys[i]
});

Here is the updated CodePen: https://codepen.io/anon/pen/JpoKLK?editors=1010

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
  • Thanks again for your help Gerardo. I'm using the graphs in Angular where am using the typescript fat arrow function `(()=>{)`. I was just reading that D3 doesn't really like the fat arrow function, is it best not to use this in D3? – ttmt Jan 30 '18 at 11:40
  • 1
    Well, the problem is that we use `this` a lot in D3... and, using arrow functions, you'll face some problems referencing `this`. – Gerardo Furtado Jan 30 '18 at 11:41
1

Use the attr() function, but make sure it's before your classed() call, because it will overwrite all you classes:

.attr('class', (_, i) => keys[i])
.classed('layer', true)
Yosef Weiner
  • 5,432
  • 1
  • 24
  • 37