Home>Article>Web Front-end> Building a News App Using React and the New York Times API
In this tutorial, I will show you how I built a news app using React and the New York Times API. This project was a great way for me to learn more about React, how to work with an API, and how to deploy a web app with Vercel.
The New York Times News App is a simple web application that lets users see the latest news from the New York Times. The app gets data directly from the New York Times API and shows it in a clean and easy-to-use interface.
Before we start coding, make sure you have the following on your computer:
1. Clone the Repository:
git clone https://github.com/tomasdevs/the-new-york-times-app.git cd the-new-york-times-app
2. Install Dependencies:
We need to install the tools for both the client and server parts of our app.
cd client npm install npm install react-transition-group cd ../server npm install
3. Set Up Environment Variables:
Create a .env file in the server folder and add your New York Times API key:
NYT_API_KEY=your_api_key_here
In theArticles.jscomponent, I used the Fetch API to get the latest news articles. Here’s how it works:
const response = await fetch( process.env.NODE_ENV === "production" ? `https://api.nytimes.com/svc/topstories/v2/home.json?api-key=${process.env.REACT_APP_NYT_API_KEY}` : `${process.env.REACT_APP_API_URL}/api/articles` );
This code makes sure that when the app is live, it gets data directly from the New York Times API. During development, it gets data from a local server, which makes testing easier.
To handle pagination, I added simple logic that divides the list of articles into pages. I also usedreact-transition-groupto add smooth animations when moving between articles:
{currentArticles.map((article, index) => ( ))}
At first, I had some problems with CORS when trying to get data from the New York Times API during local development. I solved this by setting up a simple backend server that acted as a proxy. For the live version, I fetched data directly from the API to keep things simple.
I also learned how important it is to manage environment variables properly, especially when deploying to platforms like Vercel. This is important to keep sensitive data, like API keys, safe.
This project was a great learning experience. It helped me improve my skills in React, API integration, and web deployment. I’m really happy with how the app turned out, and I’m excited to build more complex projects in the future.
If you have any feedback or suggestions, feel free to reach out or leave a comment. You can also check out the code on GitHub and try it yourself.
Try the live demo here!
Thanks for reading!
The above is the detailed content of Building a News App Using React and the New York Times API. For more information, please follow other related articles on the PHP Chinese website!