I'm building a web single-page app with react that connects with my express backend using a socket.io websocket. I checked that the socket.io script is being loaded right in my index.html file. I've also declared a variable named socket in the same place to make the socket accessible from the react component scripts. The intent is to use this variable inside my react components. But jsx compiler says:
9:2 error 'socket' is not defined no-undef
If I check the 'socket' var at chrome console everything looks right. I guess that this var should be defined at compile time, but how?
Here goes the react component code.
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { componentDidMount(){ socket.on('hello', function(){ console.log('YAY!'); }) } render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> </div> ); } } export default App;
Here goes my index.html code.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="favicon.ico"> <title>React App</title> <script src="/socket.io/socket.io.js"></script> <script type="text/javascript"> var socket = io.connect('http://localhost:3001') </script> </head> <body> <div id="root"></div> </body> </html>
first install socket.io like this:
npm install socket.io --save
then you should import socket.io as a module just like you did with react:
import socket from 'socket.io'
Solution here.
Import the right module in your component:
import io from 'socket.io-client';
Use it this way:
componentWillMount(){ this.socket = io('http://localhost:3001'); this.socket.on('hello', function(){ console.log('YAY!'); }) }
Full code:
(index.html)
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="favicon.ico"> <title>React App</title> </head> <body> <div id="root"></div> </body> </html>
React Component (App.js)
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import io from 'socket.io-client'; class App extends Component { componentWillMount(){ this.socket = io('http://localhost:3001'); this.socket.on('hello', function(){ console.log('YAY!'); }) } render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to Riact</h2> </div> </div> ); } } export default App;
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.