React-live-chat - Sockets.io

React, Socket.io, Redux-toolkit, TailwindCSS, Vite, Express, Eslint, Prettier, CORS, Morgan

Description

Fully functional and fullstack Chat live App.

  • Sockets.io for keep the conection.

Components

This is the look of the composition of the chat App.

View code
1const socket = io("", { transports: ["websocket"] });
2
3function App() {
4  const [message, setMessage] = useState("");
5  const [messages, setMessages] = useState([]);
6
7  const handleSubmit = (e) => {
8    e.preventDefault();
9    socket.emit("message", message);
10    const newMessage = {
11      body: message,
12      from: "Me",
13    };
14    setMessages([newMessage, ...messages]);
15    setMessage("");
16  };
17
18  useEffect(() => {
19    const receiveMessage = (message) => {
20      setMessages([message, ...messages]);
21    };
22
23    socket.on("message", receiveMessage);
24
25    return () => {
26      socket.off("message", receiveMessage);
27    };
28  }, [messages]);
29
30  return (
31    <div className="h-screen bg-zinc-800 text-white flex items-center justify-center">
32      <form onSubmit={handleSubmit} className="bg-zinc-900 p-10">
33        <h1 className="text-2xl font-bold my-2">Chat React</h1>
34        <input
35          type="text"
36          onChange={(e) => setMessage(e.target.value)}
37          value={message}
38          className="border-2 border-zinc-5000 p-2 text-black w-full"
39        />
40        {/* <button className='bg-blue-500'>Send</button> */}
41
42        <ul className="h-80 overflow-y-auto">
43          {messages.map((message, index) => (
44            <li
45              key={index}
46              className={`my-2 p-2 table text-sm rounded-md ${
47                message.from === "Me" ? "bg-sky-700 ml-auto" : "bg-black"
48              }`}
49            >
50              <p>
51                {message.from}: {message.body}
52              </p>
53            </li>
54          ))}
55        </ul>
56      </form>
57    </div>
58  );
59}
60
61export default App;
62

Server

See the how handle the conection in the backend, using CORS, Morgan

View code
1const app = express();
2const __dirname = dirname(
3  fileURLToPath(import.meta.url)
4); /* dirname("../client/dist") */
5console.log(__dirname);
6const server = http.createServer(app);
7const io = new SocketServer(server);
8
9app.use(cors());
10app.use(
11  morgan("dev", {
12    cors: {
13      // origin: 'http://localhost:5173'
14    },
15  })
16);
17
18io.on("connection", (socket) => {
19  console.log(socket.id);
20  //console.log('a user connected')
21  socket.on("message", (message) => {
22    socket.broadcast.emit("message", {
23      body: message,
24      from: socket.id,
25    });
26  });
27});
28
29app.use(express.static(join(__dirname, "../client/dist")));
30server.listen(PORT);
31console.log("Server started on port", PORT);
32