Using ChatGPT to create a full-stack web application in ReactJS

Using ChatGPT to create a full-stack web application in ReactJS

In this tutorial, we will demonstrate how to create a simple yet functional ToDo list app with the help of ChatGPT. We will be using Back4App for the backend, React for the frontend, and Material-UI for styling. Our main goal is to help people with little or no coding knowledge to build applications using the power of ChatGPT through a series of prompts and guidance.

Overview of Technologies

  • ChatGPT: ChatGPT is a powerful language model developed by OpenAI. It is based on the GPT-4 architecture and can be used to generate code, answer questions, and provide assistance in various tasks.
  • Back4App: Back4App is a fully managed backend platform that simplifies the process of building, hosting, and managing web and mobile applications. It is built on top of Parse, an open-source framework that offers various services like data storage, user authentication, and cloud functions.
  • React: React is a popular JavaScript library for building user interfaces. It makes it easy to create and manage complex UI components and their state.
  • Material-UI: Material-UI is a popular React component library that implements Google’s Material Design principles, providing pre-built components and theming capabilities to build beautiful and functional web applications.

Setting up Back4App

To get started with Back4App, you’ll need to create an account and a new app on the platform. Follow these steps:

  1. Sign up for a free account at https://www.back4app.com/.
  2. Log in to your account and create a new app.
  3. After creating the app, navigate to the “Dashboard” and note down your App ID, JavaScript Key, and REST API Key, as you will need them later.

Creating the Data Model

I’ve started making an introduction to chatGPT of what I wanted. I didnt gave him too much details about the data model because I was curious to see what he will produce. My prompt to chat GPT was:

Ask ChatGPT: “I need your help to create a complete ToDo List App with ChatGPT and Back4app. Let’s start by creating the data model. Can you please generate the code for create this data model using the cURL commands available on Back4app? Use the first object creation request to create the whole class.”

That was the OutPut:

curl -X POST \
  -H "X-Parse-Application-Id: zGWtprmiOpsVuVCpRfT9hmyML3ahOSf5BL5rhcaT" \
  -H "X-Parse-REST-API-Key: gk8Zy2uCWriTwmYrtFCe7oobLDTKBihF0wMlFFnu" \
  -H "Content-Type: application/json" \
  -d '{
        "title": "Sample Task",
        "description": "This is a sample task description.",
        "dueDate": {
          "__type": "Date",
          "iso": "2023-04-11T00:00:00.000Z"
        },
        "completed": false
      }' \
  https://parseapi.back4app.com/classes/Task

After that I checked Back4app and my data model was successfully created:

Using cURL to Add Sample Data

Now I asked for a chatGPT to give some sample data to fill my Class:

Ask ChatGPT: “Now give me 5 new tasks as sample data to populate my class.”

# Task 1
curl -X POST \
  -H "X-Parse-Application-Id: zGWtprmiOpsVuVCpRfT9hmyML3ahOSf5BL5rhcaT" \
  -H "X-Parse-REST-API-Key: gk8Zy2uCWriTwmYrtFCe7oobLDTKBihF0wMlFFnu" \
  -H "Content-Type: application/json" \
  -d '{
        "title": "Buy groceries",
        "description": "Purchase groceries for the week",
        "dueDate": {
          "__type": "Date",
          "iso": "2023-04-11T00:00:00.000Z"
        },
        "completed": false
      }' \
  https://parseapi.back4app.com/classes/Task

# Task 2
curl -X POST \
  -H "X-Parse-Application-Id: zGWtprmiOpsVuVCpRfT9hmyML3ahOSf5BL5rhcaT" \
  -H "X-Parse-REST-API-Key: gk8Zy2uCWriTwmYrtFCe7oobLDTKBihF0wMlFFnu" \
  -H "Content-Type: application/json" \
  -d '{
        "title": "Complete homework",
        "description": "Finish math and history assignments",
        "dueDate": {
          "__type": "Date",
          "iso": "2023-04-12T00:00:00.000Z"
        },
        "completed": false
      }' \
  https://parseapi.back4app.com/classes/Task


# Task 3
curl -X POST \
  -H "X-Parse-Application-Id: zGWtprmiOpsVuVCpRfT9hmyML3ahOSf5BL5rhcaT" \
  -H "X-Parse-REST-API-Key: gk8Zy2uCWriTwmYrtFCe7oobLDTKBihF0wMlFFnu" \
  -H "Content-Type: application/json" \
  -d '{
        "title": "Attend a doctors appointment",
        "description": "Annual check-up at the family physician",
        "dueDate": {
          "__type": "Date",
          "iso": "2023-04-13T00:00:00.000Z"
        },
        "completed": false
      }' \
  https://parseapi.back4app.com/classes/Task

# Task 4
curl -X POST \
  -H "X-Parse-Application-Id: zGWtprmiOpsVuVCpRfT9hmyML3ahOSf5BL5rhcaT" \
  -H "X-Parse-REST-API-Key: gk8Zy2uCWriTwmYrtFCe7oobLDTKBihF0wMlFFnu" \
  -H "Content-Type: application/json" \
  -d '{
        "title": "Call the bank",
        "description": "Inquire about new savings account options",
        "dueDate": {
          "__type": "Date",
          "iso": "2023-04-14T00:00:00.000Z"
        },
        "completed": false
      }' \
  https://parseapi.back4app.com/classes/Task

# Task 5
curl -X POST \
  -H "X-Parse-Application-Id: zGWtprmiOpsVuVCpRfT9hmyML3ahOSf5BL5rhcaT" \
  -H "X-Parse-REST-API-Key: gk8Zy2uCWriTwmYrtFCe7oobLDTKBihF0wMlFFnu" \
  -H "Content-Type: application/json" \
  -d '{
        "title": "Plan a weekend getaway",
        "description": "Research and book accommodations for a short trip",
        "dueDate": {
          "__type": "Date",
          "iso": "2023-04-15T00:00:00.000Z"
        },
        "completed": false
      }' \
  https://parseapi.back4app.com/classes/Task

I’ve executed the commands on my Terminal. Now my class is populated on Back4app:

Building the React Front-End

Now that we have our backend set up, let’s create a front-end for our ToDo app using React. I was not sure what React lib to use to help me create a better UI so I asked for his recommendation:

Ask ChatGPT: “Now let’s build the front-end. I need beautiful and useful front end in React. Do you recommend to use any specific component library for that?”

That’s the answer:

I’ve opted for using Material-UI then asked to create the code.

As I already had node installed on my computer it was easy to run the commands and create the project. If you do not have node installed, you can download and install here: https://nodejs.org/en/download

First I’ve created the React project:

npx create-react-app todo-app
cd todo-app

and then installed the components he recomended me on my project:

npm install @mui/material @emotion/react @emotion/styled parse

Notice that if in any moment chatGPT stops to write the answer you can ask to continue just typing: “you can continue”.

Now with the project created I’ve replaced the App.js code as per chatGPT request and also updated the keys: AppID and JavaScript Key.

This is the complete code:

import React, { useState, useEffect } from 'react';
import Parse from 'parse';
import { Container, Typography, TextField, Button, List, ListItem, ListItemText, Checkbox, IconButton } from '@mui/material';
import { Delete as DeleteIcon } from '@mui/icons-material';

// Initialize Parse with your Back4App App ID and Javascript Key
Parse.initialize('YOUR_APP_ID_HERE', 'YOUR_JAVASCRIPT_KEY_HERE');
Parse.serverURL = 'https://parseapi.back4app.com/';

const TodoItem = Parse.Object.extend('TodoItem');

function App() {
  const [todoInput, setTodoInput] = useState('');
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    fetchTodos();
  }, []);

  const fetchTodos = async () => {
    const query = new Parse.Query(TodoItem);
    query.descending('createdAt');
    try {
      const results = await query.find();
      setTodos(results);
    } catch (error) {
      console.error('Error while fetching todos:', error);
    }
  };

  const createTodo = async () => {  
    if (todoInput === '') return;

    const todoItem = new TodoItem();
    todoItem.set('title', todoInput);
    todoItem.set('completed', false);

    try {
      await todoItem.save();
      setTodoInput('');
      fetchTodos();
    } catch (error) {
      console.error('Error while creating todo:', error);
    }
  };

  const toggleTodo = async (todo) => {
    todo.set('completed', !todo.get('completed'));
    try {
      await todo.save();
      fetchTodos();
    } catch (error) {
      console.error('Error while updating todo:', error);
    }
  };

  const deleteTodo = async (todo) => {
    try {
      await todo.destroy();
      fetchTodos();
    } catch (error) {
      console.error('Error while deleting todo:', error);
    }
  };

  return (
    <Container maxWidth="sm">
      <Typography variant="h4" align="center" gutterBottom>
        ToDo List
      </Typography>
      <TextField
        fullWidth
        variant="outlined"
        label="Add a new task"
        value={todoInput}
        onChange={(e) => setTodoInput(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter') {
            createTodo();
          }
        }}
      />
      <Button fullWidth color="primary" variant="contained" onClick={createTodo}>
        Add Task
      </Button>
      <List>
        {todos.map((todo) => (
          <ListItem key={todo.id} dense>
            <Checkbox
              checked={todo.get('completed')}
              onChange={() => toggleTodo(todo)}
            />
            <ListItemText
              primary={todo.get('title')}
              secondary={todo.get('description')}
            />
            <IconButton edge="end" onClick={() => deleteTodo(todo)}>
              <DeleteIcon />
            </IconButton>
          </ListItem>
        ))}
      </List>
    </Container>
  );
}

export default App;

Running the code I could see, for my surprise, a complete functional App running on my local machine and connected to Back4app Backend:

Conclusion

In this tutorial, we demonstrated how to leverage the power of ChatGPT to build a simple ToDo list app using Back4App, React, and Material-UI. We covered setting up the backend with Back4App, creating a data model, adding sample data with cURL commands, and building a beautiful and functional front-end using React and Material-UI.

By interacting with ChatGPT through a series of prompts, we were able to generate code snippets, guidance, and instructions for each step, making it possible for users with little or no coding knowledge to build a web application.

This example showcases the potential of ChatGPT as a tool for assisting users in various tasks, including web development. With the continued advancement of AI technologies, we can expect even more sophisticated and powerful tools that can help users from diverse backgrounds and skill levels to create and develop their own projects with ease.


Leave a reply

Your email address will not be published.