简体   繁体   中英

How to put JS code inside React component

I have a React component and the JS code that I would like to place in it. I tried it but totally messed it up. Does anyone know how to do it?

mycomponent.js

 import React from "react";
    import Navbar from "./Navbar";

    const Chat = props => (
      <div>
              //Place for my Js code
      </div>
    );

    export default Chat;

javascript code

<script src="/socket.io/socket.io.js"></script>
      <script>
        var socket = io();

        socket.on('message', function(msg){
          console.log(msg);
          document.getElementById("message").innerHTML = msg;
        });
      </script>

You could wrap your code inside useEffect hook. It will triggered once the component mounted.

You have to install the sockito.io from the npm . Run > npm i socket.io-client

Adding few improvements as well.

import React, { useEffect, useRef } from "react";
import io from "socket.io-client";
const Chat = props => {
    const socket = useRef(null);
    useEffect(() => {
        connectToSocket();
        return () => {
            if (socket.current) {
                socket.current.disconnect()
            }
        }
    }, []);
    function connectToSocket() {
        console.log("Conneting to socket");
        socket.current = io('http://localhost:5000');
        socket.current.on('connect', () => console.log("Connected"));
        socket.current.on('disconnect', () => connectToSocket());
        socket.current.on('message', function (msg) {
            console.log(msg);
            document.getElementById("message").innerHTML = msg;
        });
    }
    return (<div>
        Some data
        <div id="message"></div>
    </div>)
}
export default Chat;

You should import socket.io from npm rather than using script tags in React. And the code be added like

import io from "socket.io";

const Chat = props => {
  React.useEffect(() => {
    let socket = io();

    socket.on('message', function(msg) {
      console.log(msg);
      document.getElementById('message').innerHTML = msg;
    });
  }, []);

  return <div></div>;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM