I tried my best to break the seal of ChatGPT writing front-end code, and the result...

d9b9d08edee25acde422422a5486e286.jpeg

I tried my best to break the seal of ChatGPT writing front-end code

cb6cd0da47d4f06da15c4e1e8199e653.png

introduce

ChapGPT sounds too good to be true, so let's let it write some JS code for us. I wanted to see if it could solve the tasks I do every day as a front-end developer.

Whether it's a donkey or a horse, let's go directly to the topic to find out.

Building a Popup Component in React

While it's possible, let's not start this experiment by adding some code. Let's simply ask ChatGPT to create two React components that will be the element of the popup and a button that toggles its visibility, which is how I asked in the first place:

Create a separate file with a React function component that only has buttons (button), and its name is ModalOpen. Then create a function component file called Modal separately, and there is a div in the Modal function component.

As a result, the functions and pop-up events that I didn't mention were also written out, which really shocked me!

1a4c9d2d9483a1d7c99f9ae7f64fa43c.png

ce79890a1790a163985001d9a03f69b7.png

Are you shocked after reading the above screenshots? But I don't want him to implement the functions I haven't mentioned yet, so I modified the instruction to create the code as follows:

Create a separate file with a React function component that only has buttons (button), and its name is ModalOpen. Then create a function component file called Modal separately, and there is a div in the Modal function component. Don't include events yet, just component styles.

49f181e3c88fe58134eb559004f9c37a.png

0c45e94d38629d37dd21f5ea204dec21.png

This simple task was done perfectly! Notice how it actively adds some content to the HTML elements, since it clearly understands their purpose. Not to mention the little text note at the bottom is very helpful!

Add data states and events

Next, let's go directly to a complex task and ask it to add the necessary functionality to make the button open the popup, and I gave him the instruction to modify the component code like this:

Can the code of these components be modified so that the ModalOpen component opens the pop-up box of the Modal component?

3158d22fb2cbb2f2e000d5aaea72d17e.png

15b845503eb8eecb3ce43c3feb91e890.png

Again, the execution is flawless! ChatGPT adds the necessary state, click event listeners and handlers for all of this to work properly. And the task was overfulfilled, and one more function to close the pop-up box was implemented, which was not mentioned in my instruction. It seems that he is a perfectionist. The explanation it gives is still very perfect. I feel this is a great learning tool for beginners as it not only does what you want but also explains it clearly. Obviously, you can choose to ask more questions at any time.

Create a new ParentComponet parent component

Next, we need to put these two separate components into the ParentComponet parent component. Now we can tell ChatGPT to let them write a ParentComponet parent component for us. The instruction prompt is as follows:

Can you modify the code and introduce these two components into the ParentComponet component for my convenience

d760b749ff8c42615f6eb63c23ae3f49.png

f68ead57bb5b93fa8d6c119351361712.png

0982e97410c111504904e21fed3ea3fe.png

That's right, this task has been perfectly completed, and I am very satisfied with the text notes. How do you feel here?

Add local storage

Next, we raise the bar and let it do more complex tasks, testing that it can modify the code and save the state of the modal in local storage. This allows us to save the state of the modal even after the browser window is closed. Next, I gave ChatGpt the following prompts:

Can you modify the code of the ParentComponent component to store the isModalOpen data state in the local cache (localStorage)?

70aed552b8f5402431569a2b783c7a8e.png

aaee31d3b812fb94a38aec467dcd4bb0.png

760e9041799dcaf68f616e4ccd2e0181.png

Execution is perfect again, it correctly converts the boolean to a string, it also explains to us why it has to use useEffect in the code, it's obviously not just a general copy paste from the docs, the explanation is with what we have in the code The exact variable name is to help understand, I am not too detailed, this is done by a robot, which refreshed my cognition again.

Add styles and animations

Well, let's see if it works with CSS and animations, I think it's a little trickier for AI, first time I asked:

Can you help me add some css animation effect codes, when we click on the ModalOpen component, it will make the Modal display and hide effect more natural.

c06685bcd8f081632a260909e4cf3d88.png

e42f07d187ee18748dcdd5ed465b8b50.png

7abcc95810afd45962de03505c6cc801.png

If you don’t look at this code carefully, you think it’s written correctly, ChatGPT will also doze off, and you will be fooled if you are not careful. Although it is correct at first glance, the parent component writes like this <Modal className={isModalOpen ? 'modal open ' : 'modal close'} />, we did not define open and close in the style file, in fact, add these two styles to open and close, this case is complete, and the logic of the local cache is lost, But I'm lazy and don't want to write it myself, let AI help me to finish it and see if I'm satisfied.

Next, I issued a modified prompt command to see if it works. I ordered it like this:

Please fix the style file, and you lost the logic of the local cache, please fix your code

abb6d191e7c29210fbd107c575a90ae1.png

91f70f73405de61faae5a97c88f3e431.png

7b7eadaa2d29364b2a8fc0242594951c.png

I am satisfied with the restoration so far. Are you satisfied? It seems that AI can also make mistakes and needs human assistance.

Changed to TypeScript version of the component

Next, let's continue to increase the difficulty of writing code, let him change the code of the component to the TypeScript version, and see if he can complete it. I gave the following prompts:

Hello, can you give the code of the above component to the typescript version of the component, please write the code of all components completely

5ad9f8584bff8861c13345f718d0ff35.png

Due to the screenshot problem, I can’t take a complete screenshot. I will post the final and complete code here. Everyone can help to find out the mistakes. I haven’t found the problem so far. It’s really another wow. I feel like I have magic. Let ChatGPT complete my magic. It’s very successful feel.

// ModalOpen.tsx
import React from 'react';

interface ModalOpenProps {
  onClick: () => void;
}

const ModalOpen: React.FC<ModalOpenProps> = ({ onClick }) => (
  <button onClick={onClick}>Open Modal</button>
);

export default ModalOpen;
// Modal.tsx
import React from 'react';
import './styles.css';

interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
}

const Modal: React.FC<ModalProps> = ({ isOpen, onClose }) => (
  <div className={`modal ${isOpen ? 'open' : 'close'}`}>
    <button onClick={onClose}>Close</button>
    <p>Modal content goes here</p>
  </div>
);

export default Modal;
// ParentComponent.tsx
import React, { useState, useEffect } from 'react';
import ModalOpen from './ModalOpen';
import Modal from './Modal';

const ParentComponent: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  useEffect(() => {
    const storedValue = localStorage.getItem('isModalOpen');
    if (storedValue) {
      setIsModalOpen(JSON.parse(storedValue));
    }
  }, []);

  useEffect(() => {
    localStorage.setItem('isModalOpen', JSON.stringify(isModalOpen));
  }, [isModalOpen]);

  return (
    <div className="App">
      <ModalOpen onClick={() => setIsModalOpen(true)} />
      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} />
    </div>
  );
};

export default ParentComponent;
// styles.css
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease-out;
}

.modal.open {
  opacity: 1;
  visibility: visible;
}

.modal.close {
  opacity: 0;
  visibility: hidden;
}

.modal p {
  background: white;
  padding: 1rem;
  border-radius: 0.5rem;
}

Add list data requirements

Next, we continue to increase the requirements. In the Modal component, add some properties, such as displaying the user's name and avatar. This is how I gave ChatGPT prompts:

Hello, you can modify the Modal component code based on the rewritten TypeScript version, define the following properties in the Modal component: firstName, lastName, profession, profilePhoto, these properties are all string types, and display these properties in the Modal component Content.

82573dd5e3d5ffa7acac1ec60997aba3.png

import React from 'react';
import './Modal.css';

interface ModalProps {
  firstName: string;
  lastName: string;
  profession: string;
  profilePhoto: string;
  isOpen: boolean;
  onClose: () => void;
}

const Modal: React.FC<ModalProps> = ({firstName, lastName, profession, profilePhoto, isOpen, onClose}) => {
  return (
    <div className={`modal ${isOpen ? 'open' : 'close'}`}>
      <div className="modal-content">
        <span className="close-button" onClick={onClose}>×</span>
        <p>First Name: {firstName}</p>
        <p>Last Name: {lastName}</p>
        <p>Profession: {profession}</p>
        <p>Profile Photo: {profilePhoto}</p>
      </div>
    </div>
  );
};

export default Modal;

perfect! There are no errors at all, but my instructions are clear. We know it can understand the meaning behind the variable, so I suspect it will be able to figure out the required type (we'll verify this later). As usual, we got a detailed explanation, but it's not that interesting, so let's move on.

Hello, can you continue to add an object array property of hobbies in the Modal component, its structure is as follows {nameOfHobby:string; experienceInYears:number; activelyDoing:boolean}, after the modification, please display the hobbies property in the form Data, to continue these requirements, please modify the Modal component code

For example, the screenshot after completion, the code is a bit long, only the screenshot part:

fe777daf23c94f009a915e99a2ebdfd5.png

The complete code is as follows, please review it together to see if there are any problems. I haven’t posted it yet, so I can only say it’s pretty good and perfect.

import React, { useState } from 'react';

interface Props {
  firstName: string;
  lastName: string;
  profession: string;
  profilePhoto: string;
  isOpen: boolean;
  onClose: () => void;
  hobbies: { nameOfHobby: string; experienceInYears: number; activelyDoing: boolean }[];
}

const Modal: React.FC<Props> = (props) => {
  const {
    firstName,
    lastName,
    profession,
    profilePhoto,
    isOpen,
    onClose,
    hobbies,
  } = props;

  return (
    <div className={`modal ${isOpen ? 'open' : 'close'}`}>
      <button onClick={onClose}>X</button>
      <div className="profile-info">
        <img src={profilePhoto} alt="profile" />
        <div>
          <h2>
            {firstName} {lastName}
          </h2>
          <p>Profession: {profession}</p>
        </div>
      </div>
      <table>
        <thead>
          <tr>
            <th>Hobby</th>
            <th>Experience (in Years)</th>
            <th>Actively Doing?</th>
          </tr>
        </thead>
        <tbody>
          {hobbies.map((hobby, index) => (
            <tr key={index}>
              <td>{hobby.nameOfHobby}</td>
              <td>{hobby.experienceInYears}</td>
              <td>{hobby.activelyDoing ? 'Yes' : 'No'}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default Modal;

Can you see how it adds hobbies, experience (years) and what it's currently doing on the table title? And it also understands that outputting a positive boolean converts it to "yes" or "no". It was really an experience and made me feel stressed.

Import third-party library

Next, let's see if it's possible to sort our hobby objects alphabetically, and possibly use an external library to fix that, which I hinted at like this:

Hello, in the completed Modal component, I want to sort the array of hobbies objects. According to the nameOfHobby property, you can introduce a third-party library. Please modify the code of the Modal component

df6f255e4552fbf476e36f08b15e1010.png

Completed code:

import React from 'react';
import { string, number, boolean, arrayOf } from 'prop-types';
import { sortBy } from 'lodash';

interface Hobby {
  nameOfHobby: string;
  experienceInYears: number;
  activelyDoing: boolean;
}

interface Props {
  firstName: string;
  lastName: string;
  profession: string;
  profilePhoto: string;
  hobbies: Hobby[];
  isOpen: boolean;
  onClose: () => void;
}

const Modal: React.FC<Props> = (props) => {
  const { firstName, lastName, profession, profilePhoto, hobbies, isOpen, onClose } = props;

  const sortedHobbies = sortBy(hobbies, ['nameOfHobby']);

  return (
    <div className={`modal ${isOpen ? 'open' : 'close'}`}>
      <div className="modal-header">
        <h2>{firstName} {lastName}</h2>
        <p>{profession}</p>
        <img src={profilePhoto} alt={`${firstName} ${lastName}`} />
      </div>
      <div className="modal-body">
        <h3>Hobbies:</h3>
        <table>
          <thead>
            <tr>
              <th>Name of Hobby</th>
              <th>Experience in Years</th>
              <th>Actively Doing</th>
            </tr>
          </thead>
          <tbody>
            {sortedHobbies.map((hobby) => (
              <tr key={hobby.nameOfHobby}>
                <td>{hobby.nameOfHobby}</td>
                <td>{hobby.experienceInYears}</td>
                <td>{hobby.activelyDoing ? 'Yes' : 'No'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="modal-footer">
        <button onClick={onClose}>Close</button>
      </div>
    </div>
  );
};

Modal.propTypes = {
  firstName: string.isRequired,
  lastName: string.isRequired,
  profession: string.isRequired,
  profilePhoto: string.isRequired,
  hobbies: arrayOf(
    shape({
      nameOfHobby: string.isRequired,
      experienceInYears: number.isRequired,
      activelyDoing: boolean.isRequired,
    }),
  ).isRequired,
  isOpen: boolean.isRequired,
  onClose: func.isRequired,
};

export default Modal;

Executes perfectly again: it decides to use lodash, imports it and writes out the logic to sort by the properties we ask for. Again, very impressive!

Finish

Well, this test is over here, we will not toss ChatGPT anymore, he is probably tired too.

This trial, I tried hard to break it and let him make mistakes, but it carried out my instructions almost perfectly, and seemed to understand the underlying meaning of variables like "hobbies" because it proactively added things I didn't need to ask for More needs.

It perfectly implements React components, event listeners, handling local storage, styling, animations, using external libraries and TypeScript types, and data sorting.

Personally, I don't feel intimidated (yet) by it because I think it can do simple and trivial tasks. Obviously, you need to be an experienced developer to make complex creative decisions around architecture and implementation, otherwise you can't let AI do simple development tasks for you, you need to constantly let AI help you fix mistakes.

At this stage, I can think of it as a VSCode plugin: instead of typing, I go through verbal prompts and let the AI ​​build elements for me, quickly in seconds for what would normally take me 5-10 minutes of repetition sex task. As we've seen in this test, it performs very well!

AI is scary, but eventually, it has the potential to eliminate the repetitive, boring stuff in our jobs that doesn't require creative thinking. As a result, we get things done faster and are able to spend more time doing the things we really enjoy doing!

What do you think about this? ? How will this change professions as we know them today? How would you incorporate this into your workflow as a developer? How will this affect the industry as a whole?

That’s all for today’s sharing. Here are some of my attempts. How do you use ChatGpt to write code? Welcome to share in the comment area. Thank you for reading. If you like my sharing, don’t forget to like and forward it, so that more people can see it. Finally, don’t forget to click attention. Your support will be the biggest motivation for me to share, and I will continue to output in the future Stay tuned for more content.

Source of ideas:
https://medium.com/bitsrc/i-asked-chatgpt-ai-to-write-react-and-javascript-for-me-and-i-was-shocked-detailed-analysis-d68d55be7746

By Mate Marschalko

Notes: Not translated, with Chinese example adaptation and case additions

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/129001927