Build a React.js Items Voting App Using LocalStorage & RadioButtons in Browser

Build a React.js Items Voting App Using LocalStorage & RadioButtons in Browser

Build a React.js Items Voting App Using LocalStorage & RadioButtons in Browser

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>
  );
}

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment