I have a div set up to render multiple times based on data retrieved from the database. The background color of the div corresponds to the ID received from the backend.
My goal is to change the background color of the currently selected div and remove the color from the previously selected div. Here's how I'm attempting to accomplish this:
constructor(props) {
super(props);
this.state = {
pollId: this.props.contents.post_poll_content_id,
temppollId: this.props.voted_id
}
}
componentDidMount() {
let el = document.getElementById(this.props.voted_id);
if (el) {
el.style.backgroundColor = "#0b97c4";
}
}
handleClick(id) {
this.setState({
pollId: id,
})
let el = document.getElementById(this.state.pollId);
if (el) {
el.style.backgroundColor = "#0b97c4";
}
let sel = document.getElementById(this.state.temppollId);
if (sel) {
sel.style.backgroundColor = "#FFFFFF";
}
this.props.submitvote(vote_object)
}
render() {
let {contents, submitvote, postId, voted_id} = this.props
return (
<div className="txt_vote_bar_div" style={{
color: voted_id === this.state.pollId ? 'white' : '#9da0a4'
}} id={this.state.pollId}>
<p className="txt_vote_choice"
style={{color: voted_id === this.state.pollId ? '#FFFFFF' : '#6a6a6a'}}
id={"id" + this.state.pollId}
onClick={() => {
this.handleClick(this.state.pollId);
}}> {contents.content} </p>
<p className="txt_tot_votes"
style={{color: voted_id === this.state.pollId ? '#FFFFFF' : '#6a6a6a'}}> {contents.votes}%
(Votes:)</p>
</div>
);
};
}
I initially set the background color of the div using temppollId
when the page loads, and then change the color of the div when clicking on it using pollId
.
The issue I'm facing is that this only works once because I am unable to update the last selected div's ID to my temppollId
in the handleClick
function. How can I ensure that the color of the previously selected div is removed when a new div is selected?
Thank you.