Home > front end >  How to pass socket connection to other components in React Typescript?
How to pass socket connection to other components in React Typescript?

Time:06-23

I have socket.io connection, I want to pass the original instance to other components. I am using Typescript React. It gives me error like:

Type '{ socket: Socket<DefaultEventsMap, DefaultEventsMap>; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'socket' does not exist on type 'IntrinsicAttributes'.ts(2322)

My code: main.tsx

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";
import { io } from "socket.io-client";

const socket = io("http://localhost:8081");

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <App socket={socket}/> //getting error from socket
  </React.StrictMode>
);

CodePudding user response:

I would create a wrapper around the socket, something like this (the code is in typescript):

// Singleton
class MySocket {
   public socket:Socket;
   public static instance: MySocket = new MySocket();

   private constructor() {
      socket = io("http://localhost:8081");
   }

   public doSomething(){
      //...
   }

   public doOtherThings(){
      //...
   }
}

Then I would use it like this:

// Component A
const ComponentA = () => {
   useEffect(()=>{
      MySocket.instance.doSomething();
   },[]);
}

export default ComponentA
// Component B
const ComponentB = () => {
   useEffect(()=>{
      MySocket.instance.doOtherThings();
   },[]);
}

export default ComponentB

But, with your approach I think you can go this way:

interface Props {
   socket: Socket<DefaultEventsMap, DefaultEventsMap>
}
const App = (props:Props)=>{
}

and you should be able to pass the socket instance you are creating it in the main.tsx to the App component.

  • Related