This is my first question here, so sorry if this looks a bit confusing. I'm developing an application in React.js in my internship and currently struggling with e.target to apply the CSS changes. This is my current code:
import React from 'react';
export default class Line extends React.Component {
constructor(props) {
super(props);
this.state = {
display: 'block',
border: 0
};
this.changeDisplay = this.changeDisplay.bind(this);
this.showCircle = this.showCircle.bind(this);
}
changeDisplay() {
const newDisplay = this.state.display == 'block' ? 'none' : 'block';
this.setState({ display: newDisplay });
}
showCircle(e) {
console.log(e.target);
const newCircle = this.state.border == 0 ? '2px solid #2B3438' : 0;
this.setState({
border: newCircle
});
}
render() {
return (
<div style={{ display: this.state.display }}>
<button id="Cross" onClick={this.changeDisplay}>✕</button>
<div id="Line">
<div id="InsideLine">
<img src="../../../ic/icon-linha.svg" />
<p>Line</p>
</div>
<div className="circle" id="one" onClick={(e) => this.showCircle(e)} style={{ border: this.state.border }}></div>
<div className="circle" id="two" onClick={(e) => this.showCircle(e)} style={{ border: this.state.border }}></div>
<div className="circle" id="three"></div>
<div className="circle" id="four"></div>
<div className="circle" id="five"></div>
</div>
</div>
)
}
}
In the function 'showCircle(e)', I can return from the console.log the element I just clicked as you can see in the following image: console.log has return clicked div
My doubt is: I don't really know where to put the e.target to do the changes inside the 'showCircle' function. I replaced 'this.' with 'e./e.target' and it doesn't work.
Btw, the function showCircles works, it changes the border but in all div's that call the 'showCircles' function on click.
The goal is to appear that border around the clicked color so the user knows where he just clicked.
Is it feasible to have a state for each circle? Something like that might work:
state = {
circles: {
one: 0,
two: 0,
three: 0,
// (...)
}
}
showCircle = (e) => {
let id = e.target.id
let circles = this.state.circles
if (circles[id] !== 0) {
circles[id] = 0
} else {
Object.keys(circles).forEach(c => circles[c] = 0) // Resets to initial styling
circles[id] = '2px solid #2B3438'
}
this.setState({
circles: circles,
});
}
Then just slightly change your rendered div (btw you don't need to pass the event as a parameter).
<div
className="circle"
id="one"
onClick={this.showCircle}
style={{ border: this.state.circles.one}}>
</div>