November 2023
5 pages
3m
English
Continuing from our previous tutorial (“Use ChatGPT to Extend the Generated App”), we will now add a list of high scores to the game. This is a bit more guided because I had an idea of what I was going for, now that the app is coming together:
Prompt: Create a high scores list that takes a list of scores as a prop, where each score is an object with { score, time} and time was created with Date.now().
ChatGPT: To create a high scores list component that takes a list of scores as a prop, follow these steps:
Create a new file
src/HighScores.jsand add the following code:importReactfrom'react';importstyledfrom'@emotion/styled';constHighScoresContainer=styled.div`margin-top: 20px;`;constHighScoreItem=styled.div`display: flex;justify-content: space-between;font-size: 18px;margin-bottom: 5px;`;constHighScores=({scores})=>{// Sort the scores array in descending order by scoreconstsortedScores=scores.sort((a,b)=>b.score-a.score);return(<HighScoresContainer><h3>HighScores</h3>{sortedScores.map(({score,time},index)=>{constdate=newDate(time).toLocaleString();return(<HighScoreItemkey={index}><span>{score}</span><span>{date}</span></HighScoreItem>);})}</HighScoresContainer>);};exportdefaultHighScores;Import the
HighScorescomponent insrc/App.js:importHighScoresfrom'./HighScores';