Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass socket connection to other components in React Typescript?

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>
);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading