Christopher
Stoll

Literally a Single Page App

Inspired by a few talks I saw at CodeMash, I wanted to perform some experiments with React. I just wanted to focus on the React code, not set up build pipelines, so I wanted a single page app which was literally a single page (except for the Javascript requirements, of course). Below is the template I used for my experiments. It is super simple, all it does is source react.development.js, react-dom.development.js, and babel-core from CDNs. I just wanted to document it so that I don’t have to look it up in the future. At the bottom of the page is a larger example which includes some actual React code.

<html>
<head>
  <script crossorigin
    src="https://unpkg.com/react@16/umd/react.development.js">
  </script>
  <script crossorigin
    src="https://unpkg.com/react-dom@16/umd/react-dom.development.js">
  </script>
  <script crossorigin
    src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js">
  </script>
  <script type="text/babel">
    // React code goes here
  </script>
</head>
<body>
  <div id="root"></div>
</body>
</html>

You would not want to use the in-browser babel script for production code.

<html>
<head>
  <script crossorigin
    src="https://unpkg.com/react@16/umd/react.development.js">
  </script>
  <script crossorigin
    src="https://unpkg.com/react-dom@16/umd/react-dom.development.js">
  </script>
  <script crossorigin
    src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js">
  </script>
  <script type="text/babel">
    class Timer extends React.Component {
      constructor(props) {
        super(props);
        this.state = { seconds: 0 };
        this.handleSubmit = this.handleSubmit.bind(this);
      }

      tick() {
        this.setState((prevState) => ({
          seconds: prevState.seconds + 1
        }));
        console.log('tick');
      }

      componentDidMount() {
        this.interval = setInterval(() => this.tick(), 1000);
        console.log('componentDidMount')
      }

      componentWillUnmount() {
        clearInterval(this.interval);
      }

      handleSubmit(e) {
        e.preventDefault();
        this.setState((prevState) => ({
          seconds: prevState.seconds + 100
        }));
        console.log('handleSubmit');
      }

      render() {
        return (
          <div>
            Seconds: {this.state.seconds}
            <br/><br/>
            <form onSubmit={this.handleSubmit}>
              <button>Add Expression</button>
            </form>
          </div>
        );
      }
    }

    ReactDOM.render(<Timer />, document.getElementById('root'));
  </script>
</head>
<body>
  <div id="root"></div>
</body>
</html>
Published: 2018-01-15
JavascriptReactApp