5 situations where I use ChatGPT for React Programming

Antony Leme
6 min readDec 25, 2023

--

Nowadays, a lot of people says that AI is coming to replace programmers and that with ChatGPT and all the others that are being launched, we're closer than never of this happen.

But, if you think about the past, you'll see that programmers back in the 1930s used to program with punch cards that was very tedious and time-consuming. Later, in the 1950s, 1960s, 1970s and on, the first programming languages started to appear and programmer's lives started to be way easier. So that's where I think the AI comes in. The AI is not about replace programmers, but make their lives better.

The AI is not about replace programmers, but make their lives better.

All those programming languages appeared as tools to make programming easier and I think AI is not different: it's nothing more than a tool to make life easier.

That being said, let's see how I use the ChatGPT AI to make my day at work way easier while programming with React.

1. Write TypeScript interfaces

Let's imagine that you are integrating your project with an API that doesn't come with all the types for the data provided. In a normal situation you would just make the obvious: copy and paste the objects and replace the data with the types. But what if the data is huge? This would be a very tedious and time-consuming task, just like programming with punch cards was back in the past.

So what I do is simply ask the AI to make it for me. Let's see how:

I have this object that comes from the api:

{
"coupon": {
"_id": "6570fea24e02032b8a853a91",
"name": "Post-Webinar Discount",
"code": "post-webinar-discount",
"discount": 0.1,
"plans": [
"monthly"
],
"expiresAt": "2023-01-06T23:08:54.647Z"
},
"stripeCoupon": {
"id": "post-webinar-discount",
"object": "coupon",
"created": 1700164609,
"duration": "forever",
"livemode": false,
"name": "Post-Webinar Discount",
"percent_off": 10,
"times_redeemed": 2,
"valid": true
}
}

So I ask the ChatGPT to make the typings for me:

And here is the full result:

interface CouponObject {
_id: string;
name: string;
code: string;
discount: number;
plans: string[];
expiresAt: string; // Assuming expiresAt is a string in ISO 8601 format
}

interface StripeCouponObject {
id: string;
object: string;
created: number;
duration: string;
livemode: boolean;
name: string;
percent_off: number;
times_redeemed: number;
valid: boolean;
}

interface CouponData {
coupon: CouponObject;
stripeCoupon: StripeCouponObject;
}

Perfectly done!

2. Sort arrays

Imagine that you have an array of objects and you need to sort them alphabetically by a specific key. You would normally create a function to do this, right? Now, just ask the AI:

Here is the complete result:

interface Person {
id: number;
first_name: string;
last_name: string;
}

function sortPeopleByName(people: Person[]): Person[] {
return people.sort((a, b) => {
const fullNameA = `${a.first_name} ${a.last_name}`;
const fullNameB = `${b.first_name} ${b.last_name}`;

return fullNameA.localeCompare(fullNameB);
});
}

// Example usage
const people: Person[] = [
{ "id": 1, "first_name": "Nickolaus", "last_name": "Whightman" },
{ "id": 2, "first_name": "Griz", "last_name": "Boldra" },
{ "id": 3, "first_name": "Dru", "last_name": "Addey" },
{ "id": 4, "first_name": "Kennett", "last_name": "Fawdery" },
{ "id": 5, "first_name": "Eugenius", "last_name": "Haugeh" }
];

const sortedPeople = sortPeopleByName(people);
console.log(sortedPeople);

And it even comes with explanation if you need to:

This function, sortPeopleByName, takes an array of Person objects and sorts them alphabetically based on the combined "first_name" and "last_name" properties using the localeCompare method. The resulting array is sorted by the full name.

3. Write complex logical functions

Imagine a situation where you receive from the API a bunch of data in eastern time but the user may be in a different timezone chosen in their settings. To show him the data, you would have to create a function that takes the AM/PM string and pass it to the user selected timezone. You would definitely take some time looking for the best way to do this or maybe a library that will do it for you.

So you could simply ask AI:

And the complete solution:

const convertTimezone = (timeString: string, targetTimeZone: string): string | null => (new Date(`January 1, 2000 ${timeString} UTC-5:00`)).toLocaleString('en-US', { timeZone: targetTimeZone, hour: 'numeric', minute: 'numeric', hour12: true });

4. Generate forms

Sometimes you are creating a code like a form that is so generic that it's nothing more than a boring and time-consuming task. So maybe you should consider asking the AI to do it for you:

The result:

import React, { FormEvent } from 'react';
import { Box, CustomLabel, Input } from './your-components'; // Import your components

interface FormData {
firstName: string;
lastName: string;
birthdate: string;
gender: string;
phoneNumber: string;
}

interface MyFormProps {
onSubmit: (data: FormData) => void;
}

const MyForm: React.FC<MyFormProps> = ({ onSubmit }) => {
const [formData, setFormData] = useImmer<FormData>({
firstName: '',
lastName: '',
birthdate: '',
gender: '',
phoneNumber: '',
});

const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const { name, value } = e.target;
setFormData((draft) => {
draft[name] = value;
});
};

const handleSubmit = (e: FormEvent) => {
e.preventDefault();
onSubmit(formData);
};

return (
<form onSubmit={handleSubmit}>
<Box>
<CustomLabel>First Name:</CustomLabel>
<Input
type='text'
name='firstName'
id='firstName'
value={formData.firstName}
onChange={handleChange}
required
/>
</Box>

<Box>
<CustomLabel>Last Name:</CustomLabel>
<Input
type='text'
name='lastName'
id='lastName'
value={formData.lastName}
onChange={handleChange}
required
/>
</Box>

<Box>
<CustomLabel>Birthdate:</CustomLabel>
<Input
type='date'
name='birthdate'
id='birthdate'
value={formData.birthdate}
onChange={handleChange}
required
/>
</Box>

<Box>
<CustomLabel>Gender:</CustomLabel>
<Input
as='select'
name='gender'
id='gender'
value={formData.gender}
onChange={handleChange}
required
>
<option value='male'>Male</option>
<option value='female'>Female</option>
<option value='other'>Other</option>
</Input>
</Box>

<Box>
<CustomLabel>Phone Number:</CustomLabel>
<Input
type='tel'
name='phoneNumber'
id='phoneNumber'
pattern="[0-9]{10}"
value={formData.phoneNumber}
onChange={handleChange}
required
/>
</Box>

<Input type='submit' value='Submit' />
</form>
);
};

export default MyForm;

As you can see, with the right directions, you can even get the generated code using your own custom components.

5. Generate data

In a real situation, I was working on a custom time select input and at some point I had to generate an array of strings with specified interval between the times that would be passed through props to my component. So I asked GPT to do it for me:

const generateTimeArray = (intervalMinutes: number): string[] => {
const times: string[] = [];
const startTime = new Date(2000, 0, 1, 0, 0); // January 1, 2000, 12:00 AM

for (let i = 0; i < 24 * 60 / intervalMinutes; i++) {
const time = new Date(startTime.getTime() + i * intervalMinutes * 60 * 1000);
times.push(time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true }));
}

return times;
};

// Example usage
const intervalMinutes = 30;
const timesArray = generateTimeArray(intervalMinutes);
console.log(timesArray);

This function, generateTimeArray, takes a specified intervalMinutes parameter and generates an array of times in AM/PM format with that interval. It starts from 12:00 AM and increments the time by the specified interval until 11:59 PM. The resulting array is then logged to the console. You can adjust the intervalMinutes variable to change the interval between times.

Conclusion

There are a lot of others situations that you can use AI to help you but I took only the 5 ones that I use the most. But, as you can see, you don't have to be afraid to lose your job to AI. Just think in it as another tool to help you.

And some of you may have noticed that sometimes the output code from the AI is not of the best quality. But if you insist and adjust the input, you can get best results and make some changes later if you have to.

But great power comes with great responsibilities. So have in mind that you must know when it's worth ask the AI and when it's not. Sometimes get the right input and make changes to the result to make it perfect will take you longer than if you just did it yourself.

--

--