Connect a React Application to a WebSocket

Tiempo de lectura: < 1 minuto

Today we’re going to learn how to connect our web application developed with React to a WebSocket.

Configuration of the React Application

  1. Create a New React Project:
    Create a new React project using create-react-app:
   npx create-react-app my-react-app
   cd my-react-app
  1. Install WebSocket Dependency:
    Install the react-websocket library to handle WebSocket connections in React:
   npm install --save react-websocket
  1. Implement WebSocket Component in React:
    Replace the contents of src/App.js with the following code:
   import React, { useState } from 'react';
   import { WebSocketProvider, useWebSocket } from 'react-websocket';

   function App() {
     const [message, setMessage] = useState('');
     const { sendJsonMessage } = useWebSocket('ws://localhost:8000/ws/1');

     const handleMessageChange = (e) => {
       setMessage(e.target.value);
     };

     const sendMessage = () => {
       sendJsonMessage({ message });
     };

     return (
       <div className="App">
         <h1>WebSocket React</h1>
         <input
           type="text"
           value={message}
           onChange={handleMessageChange}
         />
         <button onClick={sendMessage}>Send Message</button>
       </div>
     );
   }

   function AppWithWebSocket() {
     return (
       <WebSocketProvider url="ws://localhost:8000/ws/1">
         <App />
       </WebSocketProvider>
     );
   }

   export default AppWithWebSocket;

Make sure to replace ws://localhost:8000/ws/1 with the URL of your FastAPI server.

  1. Run the React Application:
    Run the React application:
   npm start

Visit http://localhost:3000 in your browser, and you’ll see the React application. You can type messages, send them, and see the responses from the FastAPI server through the WebSocket.

This tutorial provides a foundation for implementing WebSocket in a React application connected to a FastAPI server. You can customize and expand the application according to your specific needs.

Leave a Comment