Voting System
This is a simple vote calculator example which increments count on every click. I introduce the Stateful Component, which are defined using a class and make it easier to keep track of the application state provided component. This component example gives an idea how you add onClick event in JSX.
To create the example project for this example, open command prompt, navigate to a convenient location, and run the command as shown below :
create-react-app example3
Now just replace the placeholder content of App.js and App.css with given below content :
import React,{Component} from 'react';
import './App.css';
class App extends Component{
constructor(props){
super(props);
this.state = {
languages : [
{name: "Php", votes: 0},
{name: "Python", votes: 0},
{name: "Go", votes: 0},
{name: "Java", votes: 0}
]
}
}
vote (i) {
let newLanguages = [...this.state.languages];
newLanguages[i].votes++;
function swap(array, i, j) {
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
this.setState({languages: newLanguages});
}
render(){
return(
<>
<h1>Vote Your Language!</h1>
<div className="languages">
{
this.state.languages.map((lang, i) =>
<div key={i} className="language">
<div className="voteCount">
{lang.votes}
</div>
<div className="languageName">
{lang.name}
</div>
<button onClick={this.vote.bind(this, i)}>Click Here</button>
</div>
)
}
</div>
</>
);
}
}
export default App;
In React we need to create a constructor function for our classes that extend React classes. We are passing an argument into super(props) called "props" this will also be available in the Component constructor class. The super() function will make this available in the constructor method.
*{
margin: 0;
padding: 0;
}
body {
text-align: center;
color: #222;
font-size: 24px;
font-family: sans-serif;
}
h1 {
margin: 30px;
}
.languages {
height: 400px;
width: 400px;
margin: 10px auto;
display: flex;
flex-direction: column;
}
.language {
flex: 1;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 40px;
background-color: blanchedalmond;
border: 1px solid #222;
margin: 2px;
}
.voteCount {
border-radius: 50%;
display: flex;
justify-content: center;
align-items: center;
}
.language button {
color: green;
background-color: #0000;
border: none;
font-size: 30px;
outline: none;
cursor: pointer;
}