Skip to content

Instantly share code, notes, and snippets.

@openhoat
Last active September 9, 2021 13:31
Show Gist options
  • Save openhoat/8735dd2d46e012d27f63d6a9e49f12d4 to your computer and use it in GitHub Desktop.
Save openhoat/8735dd2d46e012d27f63d6a9e49f12d4 to your computer and use it in GitHub Desktop.

Netlify + React Demo

Deploy a react app with serverless function in minutes (online demo):

  1. Create a basic react app

    $ npx create-react-app netlify-react-demo --use-npm
  2. Go into project

    $ cd netlify-react-demo
  3. Install netlify

    $ npm i -g netlify-cli
    $ npm i -D netlify-cli
  4. Install axios & random-words

    $ npm i axios random-words
  5. Launch your IDE

    $ code .
  6. Create a serverless function ./functions/hello.js

    const randomWords = require('random-words')
    
    const handler = async (event, context) => {
      const { length } = event.queryStringParameters
      console.log('length param:', length)
      console.log('aws request ID:', context.awsRequestId)
      return {
        statusCode: 200,
        body: JSON.stringify({
          message: randomWords({ exactly: Number(length), join: ' ' }),
        }),
      }
    }
    
    module.exports = { handler }
  7. Add NPM script to ./package.json

    {
      "scripts": {
        "dev": "netlify dev"
      }
    }
  8. Create Netlify manifest ./netlify.toml

     [build]
     command = 'npm run build'
     functions = 'functions'
     publish = 'build'
    
     [dev]
     autoLaunch = false
  9. Run dev server

    $ npm run dev
  10. Run dev server

    $ npm run dev
  11. Test the servless function web service

    $ http http://localhost:8888/.netlify/functions/hello length==5
  12. Update App react component ./src/App.js to consume the web service

    import logo from './logo.svg'
    import './App.css'
    import { useState } from 'react'
    import axios from 'axios'
    
    function App() {
      const [message, setMessage] = useState()
      const [input, setInput] = useState()
    
      const fetchData = async () => {
        const length = input ? Number(input) : 1
        const params = new URLSearchParams([['length', length]])
        const results = await axios.get('/.netlify/functions/hello', { params })
        setMessage(results.data.message)
      }
    
      return (
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h2>Word generator</h2>
            <p>
              <input value={input} onChange={(e) => setInput(e.target.value)} />
            </p>
            <p>
              <button onClick={fetchData}>Click to generate words</button>
            </p>
            <p>{message}</p>
          </header>
        </div>
      )
    }
    
    export default App
  13. Deploy the web app with netlify

    • Log in to netlify

      $ netlify login
    • Create a new site

      $ netlify sites:create --name demo-hello-words
    • Link project to site

      $ netlify link
    • Build web app

      $ npm run build
    • Deploy

      $ netlify deploy
    • Test draft URL

      $ xdg-open https://6139d9ceef9e2bd79d6303a2--demo-hello-words.netlify.app
    • Deploy to main URL

      $ netlify deploy --prod
    • Browse main URL

      $ xdg-open https://demo-hello-words.netlify.app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment