Skip to content

Instantly share code, notes, and snippets.

@bfocht
Last active November 10, 2018 04:10
Show Gist options
  • Save bfocht/114e820db65d001e71d717be0f1d656e to your computer and use it in GitHub Desktop.
Save bfocht/114e820db65d001e71d717be0f1d656e to your computer and use it in GitHub Desktop.

React WorkShop

Link to Slides

Install Create React App

npm install -g create-react-app

Create chat client

create-react-app chat-client

Run the application

cd chat-client
npm start

Add socket connect to src/app.js

constructor(props) {
  super(props);

  //create a new socket connection
  //see documentation https://github.com/sockjs/sockjs-client#getting-started
  this.sock = new SockJS('https://chat-server.azurewebsites.net/chat');

  this.sock.onopen = () => {
    console.log('connection open');
  };

  this.sock.onmessage = e => {
    console.log('message received:', e.data);
  };

  this.sock.onclose = () => {
    console.log('close');
  };
}

Add the form to src/app.js

<form >
  <input type="text" placeholder="Type here to chat..." />
  <button type="submit">Send</button>
</form>

Handle form submit

handleFormSubmit(e) {
  e.preventDefault();
  this.sock.send(e.target[0].value);
}

Updated constructor

constructor(props) {
  super(props);

  this.state = {
    messages: []
  }

  //create a new socket connection
  //see documentation https://github.com/sockjs/sockjs-client#getting-started
  const sock = new SockJS('https://chat-server.azurewebsites.net/chat');

  sock.onopen = () => {
    console.log('connection to server open');
  };

  sock.onmessage = e => {
    this.setState( { messages: [...this.state.messages, e.data] });
  };

  sock.onclose = () => {
    console.log('close');
  };

  this.sock = sock;

  this.handleFormSubmit = this.handleFormSubmit.bind(this);
}

Render chat messages in component

{
  this.state.messages.map((message, index) => {
    return <div key={index}>{message}</div>
  })
}

Depoyment to GitHub Pages

Deployment instructions

github repo

https://github.com/bfocht/chat-client

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment