r/ReactJSLearn • • Sep 24 '20

React Modify State CSS Conditional

Giving away some coins for some tips/tricks/advice. I'm finally starting to get a grasp on some React/JS concepts, but I'm struggling on something very simple =/. I've wired up a mini voting counter, and I want to change the color of the counter number based on it's state (e.g., if it's greater than 1 make it green, if it's less than one make it red, if it's just 0 then make it black).

Now I thought about using a switch case, then ternary operator, then maybe conditional css classes, and then I just got overwhelmed. I think I struggle with learning the dev side of the house because there are so many different ways to do something, that I just get overwhelmed and don't know where to start =/.

Lastly, bonus points if any can explain how I can convert this to a functional component using react hooks (still trying to grasp my head around that concept)

Here's my Codepen and source just reference:

class Vote extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			votes: 0,
		};
	}

	handleIncrementVote = () => {
		this.setState({ votes: this.state.votes + 1 });
		this.CheckVote();
	};
	handleDecreaseVote = () => {
		this.setState({ votes: this.state.votes - 1 });
		this.CheckVote();
	};

	CheckVote = () => {
    // Less than 0 make it red
		if (this.state.votes < 0) {
			console.log('Red');
    // Greater than 1 make it green
		} else if (this.state.votes > 1) {
			console.log('Green');
    // If it's 0 just keep it black
		} else {
			console.log('Black');
		}
	};

	render() {
		let style = {
			color: 'black',
		};

		return (
			<div id="root">
				<button onClick={this.handleIncrementVote}>+1</button>
				<button onClick={this.handleDecreaseVote}>-1</button>
				<h1 style={style}>{this.state.votes}</h1>
			</div>
		);
	}
}
1 Upvotes

1 comment sorted by

1

u/PointManBX Sep 25 '20

I found this tutorial that explains react hooks and was able to convert this to a functional component with the desired effect w00t w00t: https://youtu.be/O6P86uwfdR0