Toggle Background Color Of Divs
I'm mapping a div so it would render according to the amount of data i have in my database. In my case my div render 4 times. (This is a poll which has 4 options.) I will explain m
Solution 1:
You should avoid actual DOM manipulations on your own. Let React take care of actual DOM manipulation. As per my understanding, I have designed as below. Please try and relate. Hope this helps.
In your question, I didn't understand the usage of state 'active', So i have not used in the below snippet. Is this what you are trying to acheive.
const contents = [
{
post_poll_content_id: 1,
content: "Soccer",
votes_percentage: 60
},
{
post_poll_content_id: 2,
content: "Cricket",
votes_percentage: 20
},
{
post_poll_content_id: 3,
content: "Basketball",
votes_percentage: 20
}
];
const votedId = 3; // Assume this is coming from database;classDemoextendsReact.Component {
constructor(props) {
super(props);
this.state = {
voteCount: 100,
voted_id: props.voted_id,
active:true
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(id) {
this.setState({
voted_id: id,
active: (id != this.state.voted_id) ? true : !this.state.active
});
}
render() {
let {contents, voted_id} = this.props;
return (
<div>
{contents.map((content, index) => {
return (
<divkey={index}className= {(this.state.voted_id===content.post_poll_content_id && this.state.active) ? "txt_vote_bar_divactive" : "txt_vote_bar_div"}
id={content.post_poll_content_id}
><pclassName="txt_vote_choice"id={content.post_poll_content_id}onClick={() => {
this.handleClick(content.post_poll_content_id);
}}
>
{content.content}
</p><pclassName="txt_tot_votes">
{content.votes_percentage % this.state.voteCount} Votes
</p></div>
);
})}
</div>
);
}
}
ReactDOM.render(<Democontents={contents}voted_id = {votedId}/>, document.getElementById("app"));
.txt_vote_bar_div {
display:block;
border:1px solid #eee;
margin: 10px;
width:20%;
text-align:center;
}
.active {
background-color:#0b97c4;
color:#FFF;
}
.txt_vote_choice {
color:'blue';
cursor:pointer;
text-decoration:underline;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><divid="app"></div>
Post a Comment for "Toggle Background Color Of Divs"