React is an easy to use JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a voting app with React and JavaScript.
Create the Project
We can create the React project with Create React App.
To install it, we run:
npx create-react-app voting-app
with NPM to create our React project.
Create the Voting App
To create the voting app, we write:
import React, { useState, useEffect } from "react";
export default function App() {
const [choice, setChoice] = useState("");
const [results, setResults] = useState({});
const vote = () => {
if (!localStorage.getItem("vote-result")) {
localStorage.setItem("vote-result", JSON.stringify({}));
}
setResults({ ...results, [choice]: (results[choice] ?? 0) + 1 });
};
useEffect(() => {
localStorage.setItem("vote-result", JSON.stringify(results));
}, [results]);
return (
<div>
<form>
<div>
<label>What's your favorite fruit?</label>
<input
type="radio"
value="apple"
checked={"apple" === choice}
onChange={(e) => setChoice(e.target.value)}
/>
apple
<input
type="radio"
value="orange"
checked={"orange" === choice}
onChange={(e) => setChoice(e.target.value)}
/>
orange
<input
type="radio"
value="grape"
checked={"grape" === choice}
onChange={(e) => setChoice(e.target.value)}
/>
grape
</div>
<button type="button" onClick={vote}>
vote
</button>
</form>
<div>
<h1>result</h1>
{Object.entries(results).map(([key, val]) => {
return (
<p key={key}>
{key}: {val}
</p>
);
})}
</div>
</div>
);
}
We create the choice state that stores the choice that the user selects.
Then we define the results state that stores the vote results.
Next, we define the vote function that gets the local storage item with the key vote-result.
If it’s not set, then we add it.
Next, we set the results state with setResults .
We make a copy of results and then add the choices to it.
?? is the nullish coalescing operator, which returns 0 only if results[choice] isn’t set or is undefined .
Then we add 1 to it to register the vote.
Next, we call useEffect with a callback that calls localStorage.setItem to store the latest result value in local storage.
Below that, we define a form with the question and the choices to choose from.
We have the radio button inputs.
We set them to different values, and we set the checked value so that they’re checked when we make the choice.
And in the onChange callback, we call setChoice with e.target.value to set choice to the selected value.
We call vote when we click on the vote button.
Below the form, we show the results to the user.
Object.entries returns an array of keys and values of the object in an array.
The array entries are the arrays of keys and values.
Conclusion
We can create a voting app easily with React and JavaScript.