Back

Build a Continent/Country Selector with GraphQL and React

23 Aug 2024

main image for Build a Continent/Country Selector with GraphQL and React

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. After doing some research, I created this updated version.

In this tutorial, we’ll build a simple React app that allows users to select a continent from a dropdown menu and display the corresponding countries. We’ll use Vite to set up the project and GraphQL to fetch data dynamically.

Step 1: Setting Up the React Project with Vite

First, create a new React project using Vite and start the development server:

npm create vite@latest continent-country-selector
cd continent-country-selector
npm install
npm run dev

Vite provides a faster and more efficient development experience compared to tools like Create React App.

Step 2: Structuring the App Component

Next, set up the basic structure of your App.jsx component. This component will manage state for continents, the selected continent, countries, and UI visibility.

Step 3: Fetching Data from the GraphQL API

We’ll use the fetch API to send GraphQL queries to https://countries.trevorblades.com/. Start by creating a reusable fetchGraphQL function:

Step 4: Fetching and Displaying Continents

Fetch the list of continents when the component mounts using useEffect, and store the result in state.

Once fetched, render the continents inside a dropdown menu:

Step 5: Fetching and Displaying Countries

When a user selects a continent, fetch the corresponding countries using another useEffect hook:

Finally, render the list of countries below the dropdown:

In this tutorial, we built a simple React app using Vite that allows users to select a continent and view the corresponding countries. By leveraging GraphQL and the fetch API, we dynamically updated the UI based on user input.

If you want to explore the full project, here’s the complete source code on GitHub.

GraphQL continent and country selector app demo