Getting started with React by building a Pokemon search application
Tags: javascript, beginners, react, tutorial
Published: 2024-05-11 11:25:24

---
title: Getting started with React by building a Pokemon search application
published: true
description: Getting started with React by building a Pokemon search application
tags: javascript, beginners, react, tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/skp6uo81vdnxa3rzpshs.jpg
---

_Originally published on [my blog](https://nikola-breznjak.com/blog/javascript/react/getting-started-with-react-by-building-a-pokemon-search-application/)._

## TL;DR

In the previous tutorial I showed you how to [get started with Vue.js 3 by building a Pokemon search application](https://dev.to/nikola/getting-started-with-vuejs-3-by-building-a-pokemon-search-application-1afn). I'm going to do the same here, but by using [React](https://react.dev/).

In this post, you'll learn how to use [create-react-app](https://create-react-app.dev/) (official React project scaffolding tool) to build a **React** application for searching Pokemon by using [Poke API](https://pokeapi.co/docs/v2#pokemon).

## Introduction - The Battle is Over Indeed

![](https://i.imgur.com/CseGOCb.png)

A few years ago, this was a popular meme. It was funny because it was true 🙂

However, it seems that the craziness has settled down a bit and that the war is seemingly over. For now. These top four (top 5 lists are overrated 😉) frameworks established themselves:

- [Angular](https://angular.io/) (93k)
- [React](https://reactjs.org/) (218k)
- [Svelte](https://svelte.dev/) (75k)
- [Vue.js](https://vuejs.org/) (45k)

I added the number of Github `*`s (at the time of this writing), but I don't want you to read into that too much 🤗

## Analysis paralysis will, well, paralyze you!

You could argue that there are other options like Ember, Mithril, or good 'ol jQuery even! However, [this tweet](https://twitter.com/JoubranJad/status/1136030060975017984) says it all:

> Developers are fighting over which frontend framework is better.. it's not like users know or care. They mostly care about the User Experience. UX should be our focus on the frontend.

Personally, I stuck to the Angular bandwagon since version 1.0, but that started losing its _ooomph_ after versions 2, 3, 4, ... sorry, lost count.

In the previous post I said that Vue.js (due to its progressive and flexible nature) is a perfect fit for teams that have to rewrite old codebases **one step at a time**.

I also said that:

> React's JSX just _seems wrong_, and some people, smarter than me, swear by that being TheRightWay™, and I guess we're not here to discuss tastes...

Well, after playing with it a bit, I can say it's not that bad and that indeed one gets used to it.

Also, I recently checked out [Svelte](https://svelte.dev/) and kinda like it, so will be doing a post like this next; stay tuned.

General 'framework war' kind of questions I tend to answer in the following way:

> Please just stop with the [analysis paralysis](https://en.wikipedia.org/wiki/Analysis_paralysis) already.
>
> Do your research, pick a framework (any framework for that matter) that the community is using, use it, and see how far it gets you.
>
> All these talks about X being slow or Y being better just make no sense until you try it yourself for your use case and preference.
>
> Besides, nowadays speed will not be a deciding factor among the top JS frameworks.

With all this out of the way, fasten your seatbelts, take a venti (or trenta) sized cup of coffee, and let's go do something practical! 💪

## The Demo App

As said in the intro, we'll build an application for searching (and showing) Pokemon by using [Poke API](https://pokeapi.co/docs/v2#pokemon).

You can fork the complete source code on [Github](https://github.com/Hitman666/PokemonSearch_React), and you can see the app in action [here](https://hitman666.github.io/pokemon-search-react/).

## Prerequisites

Make sure that you have the following tools installed:

- Node.js - here's a free but outdated [step by step guide/book](https://leanpub.com/meantodo) for both Windows and Mac. Or, really, just go to the [main website](https://nodejs.org/) and download the executable for your machine
- Git - here's a fun [getting started](https://nikola-breznjak.com/blog/miscellaneou/learn-git-fast-job-depends/) tutorial in case you're new to it

## Start a new app with create-react-app

To start the project, run the following command (in your Terminal): `npx create-react-app pokemon_search_react`

This command, as their [docs say](https://github.com/reactjs/create-react), will install and execute `create-react-app`, the official React project scaffolding tool. The output of that command will be similar to the one below:

```bash
Creating a new React app in /Users/nikola/Development/Testing/pokemon_search_react.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...


added 1490 packages in 2m

258 packages are looking for funding
  run `npm fund` for details

Initialized a git repository.

Installing template dependencies using npm...

added 67 packages, and changed 1 package in 8s

262 packages are looking for funding
  run `npm fund` for details
Removing template package using npm...


removed 1 package, and audited 1557 packages in 1s

262 packages are looking for funding
  run `npm fund` for details

8 vulnerabilities (2 moderate, 6 high)

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.

Created git commit.

Success! Created pokemon_search_react at /Users/nikola/Development/Testing/pokemon_search_react
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd pokemon_search_react
  npm start

Happy hacking!
```

## Running our scaffolded project

Let's run the commands (in terminal) noted at the end of the previous output:

```bash
cd pokemon_search_react
npm start
```

You should get this something similar to this output:

```bash
 Compiled successfully!

You can now view pokemon_search_react in the browser.

  Local:            http://localhost:3001
  On Your Network:  http://192.168.8.165:3001

Note that the development build is not optimized.
To create a production build, use npm run build.

webpack compiled successfully
One of your dependencies, babel-preset-react-app, is importing the
"@babel/plugin-proposal-private-property-in-object" package without
declaring it in its dependencies. This is currently working because
"@babel/plugin-proposal-private-property-in-object" is already in your
node_modules folder for unrelated reasons, but it may break at any time.

babel-preset-react-app is part of the create-react-app project, which
is not maintianed anymore. It is thus unlikely that this bug will
ever be fixed. Add "@babel/plugin-proposal-private-property-in-object" to
your devDependencies to work around this error. This will make this message
go away.
```

⚠️ If you're bothered by the seeming error-like output, then just add the following code to your `package.json` file:

```javascript
"devDependencies": {
  "@babel/plugin-proposal-private-property-in-object": "^7.16.7"
},
```

You should see the following page in your browser if you open http://localhost:3001. Please note that the port (number after `localhost:`) could be different. Usually it's 3000, but I had some other stuff running at that port, so it took the next available one.

![](https://i.imgur.com/GMFzt7r.png)

## Folder structure

Now, let's open this project in the editor of your choice (I'm using [Visual Studio Code](https://code.visualstudio.com/)), and you should see something like this:

![](https://i.imgur.com/bAjDQhF.png)

⚠️ This is an introduction tutorial, to get you running fast, so I won't be going into any specific details and will be only focusing on the `src` folder.

## Add content

OK, so let's add something to our app.

But, where to start? 🤔

Well, one of the first things I do when I come to a project for the first time is to look at the generated output. Then I try to find the strings corresponding to that output within the source code.

So, if you search for the string `Learn React`, you'll see the string is within the `App.js` file. This file contains the following code:

```javascript
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;
```

Without knowing much about React, you can see where you would change the `Learn React` text. So, let's change that to `Welcome to Pokemon Search`. Save that, and voila!, you'll see the change reflected immediately in your browser.

If you're new to web dev, you may not appreciate the usefulness of the so-called hot-reload. Back in the day, we had to refresh the browser after each save. Yeah, yeah, I know: #okboomer 🫣

## Add some style

I borrowed the image (hope they don't mind) from [Wikipedia](https://en.wikipedia.org/wiki/Pok%C3%A9mon) and saved it in the `src` folder as `logo.png`, added a search input, and styled it a bit to match it with the Pokemon style. _In case you're wondering, I asked ChatGPT to help with coming up with the style_ 🙂

Here's the final code that I came up with in `App.js`:

```js
import logo from './logo.png';
import './App.css';

function App() {
  return (
    <div className="App">
      <header>
        <img alt="react logo" className="logo" src={logo} />
      </header>

      <main>
        <div className="search-container">
          <input className="search-box" type="text" placeholder="Search..." />
        </div>
      </main>
    </div>
  );
}

export default App;
```

And the CSS in the `App.css` file:

```css
body {
  background: linear-gradient(to right, #FDDF3C, #3B4CCA);
}

header {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.logo {
  margin: 0 2rem 0 0;
}

.search-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 10px;
}

.search-box {
  width: 30%;
  height: 50px;
  font-size: 1.5em;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin: 40px 0;
  text-align: center;
}
```

The way this looks now is as follows: ![](https://i.imgur.com/hrX5ZR6.png)

_If you get stuck in any of the above steps, please reach out in the comments, and I'll be happy to help._

## Pokemon API

Finally, we come to the cool part 🥶, and that is to fetch some data from the PokeAPI and show it in our app.

How do we get this API? Well, if you do a simple Google search for `pokemon api` and open the [first link](https://pokeapi.co/), you'll also get to the [documentation](https://pokeapi.co/docs/v2) for their API.

By looking at the docs, you can find that the API endpoint that lists all the available Pokemon is this: https://pokeapi.co/api/v2/pokemon. There's a total of 1302 records.

Now, fetching all this data every time you load your app would be a bad idea from the performance standpoint, but also from their [fair use](https://pokeapi.co/docs/v2#fairuse) policy.

So, what we will do is open [this link](https://pokeapi.co/api/v2/pokemon?limit=1320) which will fetch all 1320 Pokemon endpoints. The output looks like this:

![](https://i.imgur.com/BlKuxTW.png)

Now, save this output (just Command + S or Ctrl + s if you're on Windows) to a local file that we'll name `pokemonapi.json` and place it in the `src/` folder.

> ⚠️ I just want to give proper props to [PokeAPI](https://pokeapi.co/) for their awesome service 👏

_For our demo purposes, this will be fine, but if you'd like to deploy this somewhere where you'd get a lot of traffic (or, if the main list of Pokemon changes), you'd have to cache the responses. We'll tackle this in another blog post, but just something to keep in mind._

## Show the data

Now we'll want to list all the Pokemon that we have in the `pokemonapi.json` file. To do that, we'll add some code at the top of the `App.js` file that looks like this:

```javascript
import pokemonData from "./pokemonapi.json";
import React, { useState } from "react";
```

And then, inside the `function App()`:

```javascript
  const [pokemonList, setPokemonList] = useState(pokemonData.results);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedPokemon, setSelectedPokemon] = useState(null);

  const filteredPokemonList = pokemonList.filter((pokemon) =>
    pokemon.name.includes(searchTerm)
  );
```

`filteredPokemonList` function returns the list of pokemon that we loaded from the `pokemonapi.json` file and filters them by what we enter in the input box.

We'll add this portion of JSX just below the `search-container` div:

```JSX
<ul>
  {filteredPokemonList.map((pokemon) => (
    <li key={pokemon.id} className="pokemon-item">
      <a href="#">{pokemon.name}</a>
    </li>
  ))}
</ul>
```

And, we'll add a bit of CSS:

```css
.pokemon-item {
  float: left;
  margin: 10px;
}
.pokemon-item a {
  color: #000;
  text-decoration: none;
  font-size: 16px;
  transition: color 0.3s ease;
  text-transform: capitalize;
}

.pokemon-item a:hover {
  color: #3B4CCA;
}

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 5px;
  list-style: none;
}
```

Doing this, you should have your app look like this:

![](https://i.imgur.com/9CtWoYV.png)

## Get additional details about each Pokemon

If you open any of the URLs that you see in the `pokemonapi.json` file, you will get an output like this:

![](https://i.imgur.com/0e52ATX.png)

To show some additional information about a certain Pokemon (once clicked on its name in the list), we'll update the `a` tag inside the `li`:

```JSX
<li key={pokemon.id} className="pokemon-item">
  <a href="#" onClick={() => showPokemon(pokemon.url)}>{pokemon.name}</a>
</li>
```

On the click event we attached the `showPokemon` function (by using `onClick`) and passed it the URL that we get in the main API call (loaded from the JSON file).

Now we should define this function:

```JS
const showPokemon = async (url) => {
  const response = await fetch(url);
  if (!response.ok) {
    console.error(`Error fetching Pokemon: ${response.statusText}`);
    return;
  }

  const data = await response.json();
  setSelectedPokemon(data);
}
```

To show the selected Pokemon, we'll add a bit of JSX between the `search-container` div and the `ul`:

```JSX
{selectedPokemon && (
  <div className="pokemon-details">
    <h2>{selectedPokemon.name}</h2>
    <img
      src={selectedPokemon.sprites.front_default}
      alt={selectedPokemon.name}
    />
    <p>Height: {selectedPokemon.height}</p>
    <p>Weight: {selectedPokemon.weight}</p>

    {selectedPokemon.stats.map((stat, index) => (
      <div key={index}>
        <p>
          {stat.stat.name}: {stat.base_stat}
        </p>
      </div>
    ))}
  </div>
)}
```

We're using `selectedPokemon &&` so that the line `{{ selectedPokemon.name }}` doesn't throw an error for trying to access a property that doesn't exist on the object `selectedPokemon` (which is initialized as `null` in the beginning: `const [selectedPokemon, setSelectedPokemon] = useState(null);`).

BTW, `useState` is a so-called React Hook that essentially enables you to update a certain variable.

Anyways, back on point; we're using `map` to loop through all the elements of the `stats` array and output the `name` and `base_stat` properties.

To make it look nicer, we'll use a bit of CSS:

```CSS
.pokemon-details {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 30%;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #000;
  border-radius: 10px;
  color: #000;
  text-transform: capitalize;
}

.pokemon-details img {
  width: 100px;
  height: 100px;
}
```

## Two-way data binding
Right now if you test your app and type something in the search box, it will **not** filter the list of Pokemon.

You may remember that in Vue.js, we achieved this by using the `v-model`. However, in React, there isn't a direct equivalent to Vue's `v-model` for two-way data binding. In React we can achieve a similar effect by using a combination of state and event handlers.

To do this, we'll update the `input` tag to this:

```HTML
<input className="search-box" type="text"
  placeholder="Search..." 
  value={searchTerm} 
  onChange={event => setSearchTerm(event.target.value)}
/>
```

In this code, `searchTerm` is a state variable that is set as the value of the input field. The `onChange` event handler updates `searchTerm` whenever the user types something into the input field. This creates a two-way data binding effect similar to Vue's v-model.

Go try it out! The app is now fully functional 💪

## All the code


For reference, for those following the tutorial to the dot, here's the full listing of `App.js` file:

```JSX
import logo from "./logo.png";
import "./App.css";
import pokemonData from "./pokemonapi.json";
import React, { useState } from "react";

function App() {
  const [pokemonList, setPokemonList] = useState(pokemonData.results);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedPokemon, setSelectedPokemon] = useState(null);

  const filteredPokemonList = pokemonList.filter((pokemon) =>
    pokemon.name.includes(searchTerm)
  );

  const showPokemon = async (url) => {
    const response = await fetch(url);
    if (!response.ok) {
      console.error(`Error fetching Pokemon: ${response.statusText}`);
      return;
    }

    const data = await response.json();
    setSelectedPokemon(data);
  };

  return (
    <div className="App">
      <header>
        <img alt="react logo" className="logo" src={logo} />
      </header>

      <main>
        <div className="search-container">
          <input className="search-box" type="text" placeholder="Search..." 
          value={searchTerm} 
          onChange={event => setSearchTerm(event.target.value)}
          />
        </div>

        {selectedPokemon && (
          <div className="pokemon-details">
            <h2>{selectedPokemon.name}</h2>
            <img
              src={selectedPokemon.sprites.front_default}
              alt={selectedPokemon.name}
            />
            <p>Height: {selectedPokemon.height}</p>
            <p>Weight: {selectedPokemon.weight}</p>

            {selectedPokemon.stats.map((stat, index) => (
              <div key={index}>
                <p>
                  {stat.stat.name}: {stat.base_stat}
                </p>
              </div>
            ))}
          </div>
        )}

        <ul>
          {filteredPokemonList.map((pokemon) => (
            <li key={pokemon.id} className="pokemon-item">
              <a href="#" onClick={() => showPokemon(pokemon.url)}>
                {pokemon.name}
              </a>
            </li>
          ))}
        </ul>
      </main>
    </div>
  );
}

export default App;
```

And here's the full contents of the `App.css` file:

```css
body {
  background: linear-gradient(to right, #FDDF3C, #3B4CCA);
}

header {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.logo {
  margin: 0 2rem 0 0;
}

.search-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  gap: 10px;
}

.search-box {
  width: 30%;
  height: 50px;
  font-size: 1.5em;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin: 40px 0;
  text-align: center;
}

.pokemon-item {
  float: left;
  margin: 10px;
}
.pokemon-item a {
  color: #000;
  text-decoration: none;
  font-size: 16px;
  transition: color 0.3s ease;
  text-transform: capitalize;
}

.pokemon-item a:hover {
  color: #3B4CCA;
}

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 5px;
  list-style: none;
}

.pokemon-details {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 30%;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #000;
  border-radius: 10px;
  color: #000;
  text-transform: capitalize;
}

.pokemon-details img {
  width: 100px;
  height: 100px;
}

.pokemon-details p {
  margin: 5px;
}
```

## B e a utiful

At this point, we can search for some Pokemon (my son's favorite is, ofc, Pikachu), and if we click on it, we'll get this:

![search results - pikachu](https://i.imgur.com/DEWVNg7.png)

## Deployment

If you'd like to host this on your web server, then first run `npm run build` and you'll get an output similar to this:

```bash
> pokemon_search_react@0.1.0 build
> react-scripts build

Creating an optimized production build...
Compiled with warnings.

[eslint] 
src/App.js
  Line 64:15:  The href attribute requires a valid value to be accessible. Provide a valid, navigable address as the href value. If you cannot provide a valid href, but still need the element to resemble a link, use a button and change it with appropriate styles. Learn more: https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/HEAD/docs/rules/anchor-is-valid.md  jsx-a11y/anchor-is-valid

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

File sizes after gzip:

  58.34 kB (-1 B)  build/static/js/main.b3bd969c.js
  1.78 kB          build/static/js/453.bd7a2879.chunk.js
  677 B            build/static/css/main.af098727.css

The project was built assuming it is hosted at /.
You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.
You may serve it with a static server:

  serve -s build

Find out more about deployment here:
  https://cra.link/deployment
```

Now all you have to do is take the contents of the `build` folder (you may remember that in Vue that folder was called `dist`) and 'paste' it on your static web server.

If you don't have a server of your own, then Vite has an extensive [description](https://vitejs.dev/guide/static-deploy) for deploying your static pages to many popular services like Github Pages, Netlify, Vercel, Surge, etc.

You can deploy to Github Pages in under 2 minutes by following their [documentation](https://pages.github.com/).

Just for brevity sake the steps are as follows:

- create a new public Github repository and name it `username.github.io`, where `username` is your `username` on GitHub.
- clone the repo with `git clone https://github.com/username/username.github.io`
- inside the folder copy the contents of the `build` folder
- commit and push the changes:

```bash
git add --all 
git commit -m "Initial commit"
git push -u origin main
```

Now your site will be visible online at [https://username.github.io](https://username.github.io) (again, where `username` is your Github username)

You can see my deployment live [here](https://hitman666.github.io/pokemon-search-react/).

⚠️ If you'll have multiple folders in Github pages, then before using the `npm run build` command, you'll want to set the `homepage` variable in the `package.json` file to that folder. Example: `"homepage": "/pokemon-search-react"`.

## Conclusion

In this tutorial, you learned how to get started with using React by building an application for searching Pokemon by using PokeAPI and making it publically accessible via Github Pages.


I intend to cover at least two more frameworks in the future blog posts, so stay tuned. Finally, out of curiosity, which one do you prefer so far: React or Vue.js? I'm looking to test Svelte next, but curious which one you'd like to see me cover.

Please leave any comments and feedback in the discussion section below, and thank you for reading!