Skip to content

Instantly share code, notes, and snippets.

@akshaymnair
Forked from bfocht/react-workshop.md
Created January 13, 2018 17:32
Show Gist options
  • Save akshaymnair/658296e6734f6d67300deac97b358277 to your computer and use it in GitHub Desktop.
Save akshaymnair/658296e6734f6d67300deac97b358277 to your computer and use it in GitHub Desktop.

Arizona Hacks - React WorkShop

Link to Slides

Install REACT

npm install -g create-react-app

Create the react application

create-react-app chat-client

Run the application

cd chat-client
npm start

Add the form to src/app.js

<div className="container">
  <form onSubmit={this.handleFormSubmit}>
    <div className="form-group">
      <div className="input-group">
        <input type="text" ref="messageText" className="form-control" placeholder="Type here to chat..." />
        <span className="input-group-btn">
          <button type="submit" className="btn btn-primary">Send!</button>
        </span>
      </div>
    </div>
  </form>
</div>

Add bootstrap to public/index.html

(http://getbootstrap.com/)[http://getbootstrap.com/]

<!-- Latest compiled and minified CSS from http://getbootstrap.com/-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">

component constructor

constructor(props) {
  super(props);

  this.state = {
    messages: []
  }

  //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');
  };

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

handle form submit

handleFormSubmit(e) {
  e.preventDefault();
  let text = this.refs.messageText.value;
  this.sock.send(text);
}

render chat messages in component

<ul className="list-group">{
  this.state.messages.map(message => {
    return <li className="list-group-item" key={i++}>{message}</li>
  })}
</ul>

add deploy scripts to package.json for gh-pages

"predeploy": "npm run build",
"deploy": "gh-pages -d build"

add homepage to package.json

"homepage": "http://{username}.github.io/chat-client"

publish to github pages

npm run deploy

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