I have a ReactJS component that I use in multiple instances. I'm trying to change the CSS elements of each component on click.
Initially, I tried referencing the specific component element by ID, but the issue is that all instances currently share the same ID, causing changes to affect all components.
I'm considering passing a unique reference to each component, but I'm unsure how to implement this in the HTML IDs of the elements. In Angular, a solution would look like this:
<span id="{{ 'object-' + $component_idx }}"></span>
Is there a similar approach in React? Or perhaps a better way to achieve my goal?
This is what I am currently doing:
Calling the component instance in the parent:
<Entry
title={instance_title}
number={i}
/>
Creating an Entry component:
class Entry extends React.Component {
constructor(props) {
super(props);
this.state = { preference: 4 };
}
preferencer(idx) {
// Change emoji size
let oldPref = this.state.preference;
if (idx == this.state.preference) {
this.state.preference = 4;
document.getElementById("emo" + idx).style.transform = "scale(1)";
} else if (idx != this.state.preference) {
this.state.preference = idx;
document.getElementById("emo" + idx).style.transform = "scale(2)";
if (oldPref != 4) {
document.getElementById("emo" + oldPref).style.transform = "scale(1)";
}
}
}
render() {
return (
<Wrapper>
<EmojiWrap id="emo0" onClick={() => this.preferencer(0)}>
🤢{" "}
</EmojiWrap>
<EmojiWrap id="emo1" onClick={() => this.preferencer(1)}>
😶
</EmojiWrap>
<EmojiWrap id="emo2" onClick={() => this.preferencer(2)}>
😍
</EmojiWrap>
</Wrapper>
);
}
}
export default Entry;
Thank you!