Search code examples
javascriptreactjssocketssocket.iocdn

ReactJS " io is not defined" using CDN link of SOCKET IO


I do not want to use Npm package for my project So i try to use CDN link to use SOCKET IO in client side .

Please Note that same CDN link is working fine in normal html/css js but not in react project.

I put CDN link index.html inside Pubic folder of React project

here it is:

<script defer src="https://cdn.socket.io/3.1.3/socket.io.min.js"  integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous" ></script>

Thanks in Advance

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

I put this constant before class component


Solution

  • You could create a React Hook which uses a React useEffect that just uses Javascript to query select the head component and create a script element to manually set the src.

    Or you could use a library like React Helmet which lets you handle script injection easily within React without needing to install the module.

    EDIT*

    The absolute bare-bones way to access the io methods in React if you are using placing the script inside /public/index.html is:

    const socket = window.io();