I have been learning how to use
GraphQL to link my applications to a database. I found
this tutorial by Web Dev Simplified, but some of the content was outdated. So I did some research and from that tutorial, I created this one. In this tutorial, we'll walk through the process of building a simple React app that allows users to select a continent from a dropdown menu and display the corresponding countries in that continent. We will use Vite, a fast frontend build tool, to set up our React project. Additionally, we'll leverage GraphQL to fetch the data dynamically, making our app flexible and efficient.
Step 1: Setting Up the React Project with Vite
First, let's create a new React project using Vite:
npm create vite@latest continent-country-selector
cd continent-country-selector npm install npm run dev
This command initializes a new React project with Vite and starts the development server. Vite provides a faster, more efficient development experience compared to traditional tools like Create React App.
Step 2: Structuring the App Component
Let's start by setting up the basic structure of our App.jsx component. This component will manage the state for continents, selected continent, countries, and visibility.
Step 3: Fetching Data from the GraphQL API
We'll use the
fetch API to send GraphQL queries to an endpoint that provides information about continents and countries. The API we'll use is hosted at
https://countries.trevorblades.com/.
Let's create a reusable fetchGraphQL function that handles sending queries to the API:
Step 4: Fetching and Displaying Continents
We need to fetch the list of continents when the component mounts. We'll use the useEffect hook for this, and store the continents in the continents state. Update the useEffect hook to fetch continents:
Now, we can render the continents in the dropdown menu:
Step 5: Fetching and Displaying Countries
Next, we'll fetch the countries of the selected continent when the user selects a continent from the dropdown.
Add the following useEffect hook:
This hook will fetch the countries based on the selected continent code (inputValue) and store them in the countries state. Finally, let's display the countries below the dropdown:
In this tutorial, we've built a simple React app using Vite that allows users to select a continent and view the corresponding countries. We used the fetch API to send GraphQL queries to a remote server, dynamically updating our UI based on user input. Vite's fast development server and optimized build process make it an excellent choice for modern React development. I hope this guide has helped you understand how to work with GraphQL in a React environment using Vite. Happy coding!
Here is a link to the full project code