Reputation: 15
I'm attempting to create an "upvote/downvote" thumbs up and thumbs down similar to the Reddit upvote and downvote system.
I want to be able to change the state/color of the object to green if thumbs up is clicked or red if thumbs down is clicked.
BUT, I don't want the user to be able to click thumbs up twice and go from green to default white... Any ideas?
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {counter: 0}
}
increment = (e) => {
e.preventDefault();
this.setState({
counter: this.state.counter + 1
});
}
decrement = (e) => {
e.preventDefault();
this.setState({
counter: this.state.counter - 1
});
}
render() {
return (
<div className="voting">
{this.state.counter}
<button className="upvoteBtn" type="submit" onClick={this.increment}>
<i className="fa fa-thumbs-up ml-2 mr-2"/>
</button>
<button className="downvoteBtn" type="submit" onClick={this.decrement}>
<i className="fa fa-thumbs-down ml-2 mr-2"/>
</button>
</div>
)
}
}
Upvotes: 0
Views: 4120
Reputation: 1381
This might give you an idea. Once either up or down button clicked, it will disable both buttons. You can also implement your counter function inside handleUp and handleDown:
class Sample extends React.Component {
constructor(props) {
super(props);
this.state = {
colorUp: 'secondary',
colorDown: 'secondary',
clicked: false
};
this.handleUp = this.handleUp.bind(this);
this.handleDown = this.handleDown.bind(this);
}
handleUp(event) {
if (this.state.clicked === false) {
this.setState({
colorUp: 'success',
clicked: true
});
}
}
handleDown(event) {
if (this.state.clicked === false) {
this.setState({
colorDown: 'danger',
clicked: true
});
}
}
render() {
return (
<div>
<ReactBootstrap.Button className='ml-3' variant={this.state.colorUp} onClick={this.handleUp} disabled={this.state.clicked}>Up</ReactBootstrap.Button>
<ReactBootstrap.Button className='ml-3' variant={this.state.colorDown} onClick={this.handleDown} disabled={this.state.clicked}>Down</ReactBootstrap.Button>
</div>
);
}
}
ReactDOM.render(
<Sample />,
document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js" crossorigin></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" crossorigin="anonymous">
<div id="root" />
Upvotes: 2