Today we’re going to learn how to connect our web application developed with React to a WebSocket.
Configuration of the React Application
- Create a New React Project:
Create a new React project usingcreate-react-app
:
npx create-react-app my-react-app cd my-react-app
- Install WebSocket Dependency:
Install thereact-websocket
library to handle WebSocket connections in React:
npm install --save react-websocket
- Implement WebSocket Component in React:
Replace the contents ofsrc/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.
- 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.