Step-by-Step Guide: Build a Real-Time Voting App with WebSockets, React & TypeScript

Sachin KumarSachin Kumar
3 min read

In the realm of web development, the ability to create real-time applications is a game-changer. Imagine building a voting app that updates in real-time as users cast their votes. In this tutorial, we'll guide you through the process of creating a real-time voting app using WebSockets, React, and TypeScript. Let's embark on this exciting journey to harness the power of modern web technologies!

Prerequisites:

  • Basic understanding of React and TypeScript

  • Node.js and npm (Node Package Manager) installed on your system

Step 1: Setting Up Your Environment

Before we dive into coding, make sure you have Node.js and npm installed. Create a new directory for your project and navigate to it using your terminal.

Step 2: Initializing Your Project

Run the following command to initialize your project with npm:

bashCopy codenpm init -y

This will create a package.json file that will track your project's dependencies.

Step 3: Installing Dependencies

We'll need to install the necessary packages: express, socket.io, react, and typescript. Use the following command:

bashCopy codenpm install express socket.io react react-dom typescript

Step 4: Setting Up the Server

Create a file named server.ts in your project directory. This will be the backend server for your real-time voting app.

typescriptCopy code// server.ts
import express from 'express';
import http from 'http';
import socketIO from 'socket.io';

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

io.on('connection', (socket) => {
  console.log('A user connected');

  socket.on('vote', (option) => {
    io.emit('newVote', option);
  });

  socket.on('disconnect', () => {
    console.log('A user disconnected');
  });
});

server.listen(3001, () => {
  console.log('Server is running on port 3001');
});

Step 5: Creating the React App

In your project directory, run the following command to create a new React app:

bashCopy codenpx create-react-app client --template typescript

This will create a client directory with your React app.

Step 6: Building the Voting Component

Inside the src directory of the client folder, create a new file named Voting.tsx.

tsxCopy code// Voting.tsx
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';

const socket = io('http://localhost:3001');

const Voting: React.FC = () => {
  const [votes, setVotes] = useState<{ [key: string]: number }>({ optionA: 0, optionB: 0 });

  useEffect(() => {
    socket.on('newVote', (option: string) => {
      setVotes((prevVotes) => ({ ...prevVotes, [option]: prevVotes[option] + 1 }));
    });
  }, []);

  const handleVote = (option: string) => {
    socket.emit('vote', option);
  };

  return (
    <div>
      <h1>Real-Time Voting App</h1>
      <div>
        <button onClick={() => handleVote('optionA')}>Vote for Option A</button>
        <button onClick={() => handleVote('optionB')}>Vote for Option B</button>
      </div>
      <div>
        <p>Option A: {votes.optionA}</p>
        <p>Option B: {votes.optionB}</p>
      </div>
    </div>
  );
};

export default Voting;

Step 7: Integrating Voting Component

Open the src/App.tsx file in the client directory and replace its content with the following:

tsxCopy code// App.tsx
import React from 'react';
import './App.css';
import Voting from './Voting';

function App() {
  return (
    <div className="App">
      <Voting />
    </div>
  );
}

export default App;

Step 8: Running Your App

In one terminal window, navigate to your project directory and run the server:

bashCopy codenode server.ts

In another terminal window, navigate to the client directory and run the React app:

bashCopy codenpm start

Conclusion

Congratulations! You've successfully created a real-time voting app using WebSockets, React, and TypeScript. This tutorial has introduced you to the power of real-time communication and how it can enhance user experiences in modern web applications. With this foundation, you can explore further by adding more features, improving the UI/UX, and scaling your app to accommodate larger audiences. Happy coding!

0
Subscribe to my newsletter

Read articles from Sachin Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sachin Kumar
Sachin Kumar