I have a component that renders multiple things, one of that is an array of spans.
Here is a part of my code:
<code>class MyComponent ... {
private targetSpan = HTMLElement;
componentDidMount() {
//Here I get some data that fills an array that has 6 values
}
...
...
...
private setActive(value) {
let target = this.targetSpan;
if (target.classList.contains('active')) {
target.classList.remove('active');
//do more things
}
else {
target.classList.add('active');
//do even more things
}
}
private splitMyThings() {
const returnThings: any[] = [];
forEach(array, thing => {
returnThings.push(
<span class="thing" onClick={() => this.setActive(thing)} ref={elem => this.targetSpan = elem}>
{thing}
</span>
);
});
}
render() {
...
return <div class="container">
...
<div class="myTargets">
{this.splitMyThings()}
</div>
...
</div>;
}
}
</code>
<code>class MyComponent ... {
private targetSpan = HTMLElement;
componentDidMount() {
//Here I get some data that fills an array that has 6 values
}
...
...
...
private setActive(value) {
let target = this.targetSpan;
if (target.classList.contains('active')) {
target.classList.remove('active');
//do more things
}
else {
target.classList.add('active');
//do even more things
}
}
private splitMyThings() {
const returnThings: any[] = [];
forEach(array, thing => {
returnThings.push(
<span class="thing" onClick={() => this.setActive(thing)} ref={elem => this.targetSpan = elem}>
{thing}
</span>
);
});
}
render() {
...
return <div class="container">
...
<div class="myTargets">
{this.splitMyThings()}
</div>
...
</div>;
}
}
</code>
class MyComponent ... {
private targetSpan = HTMLElement;
componentDidMount() {
//Here I get some data that fills an array that has 6 values
}
...
...
...
private setActive(value) {
let target = this.targetSpan;
if (target.classList.contains('active')) {
target.classList.remove('active');
//do more things
}
else {
target.classList.add('active');
//do even more things
}
}
private splitMyThings() {
const returnThings: any[] = [];
forEach(array, thing => {
returnThings.push(
<span class="thing" onClick={() => this.setActive(thing)} ref={elem => this.targetSpan = elem}>
{thing}
</span>
);
});
}
render() {
...
return <div class="container">
...
<div class="myTargets">
{this.splitMyThings()}
</div>
...
</div>;
}
}
When I watch the result in a Browser, all the spans show up how I want, only thing that doesnt seem to work correctly is the setActive-Function (or even something else?).
No matter what span I click, everytime only the last one gets the active-class, I absolutely cant figure out how to fix that.
Hope someone has a quick and simple solution or idea how to achieve that,
thanks in advance!