Back

Building an Encyclopedia with React and Wikipedia Search API

Building an Encyclopedia with React and Wikipedia Search API

The evolution of APIs has drastically changed the way our applications are being developed to scale. One can build an API and reuse it in subsequent applications without having to reinvent the wheel. In this tutorial, I will be teaching you how to build an encyclopedia using Wikipedia search API. Great right? Let’s get started.

Getting started

I have already pushed the user interface with the components for this project to Github. Follow the steps below to get a copy of the code.

  1. Click on the Github link
  2. Download or Fork the repository to have a copy of it
  3. Unzip or clone the repository from your Github to your working directory
  4. Open your commad line
  5. Run npm install to install the required packages
  6. Run npm start to get the project started.

Wikipedia Search API

Wikipedia Search API is an Open-source search API, created by the Wikimedia Foundation to enable you to integrate a full-text search functionality in your projects. The API endpoint is in the form https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&inprop=url&utf8=&format=json&origin=*&srlimit=20&srsearch=word. Click on this link to know more about the API.

Making API Request

Open encyclopedia/components/Search.jsx , import react useState to handle our state changes and the Word component to display of the search results from the API.

import Word from "./Words";
import { useState } from "react";

Next, create a state to store the search results, the state will have an empty object by default.

const [result, setResult] = useState({})

Next, we need to create a function to make a request to the API. This function will request the API with the word from the input field, then return the search word’s meanings. Before sending a request to the API, you remove all whitespaces from both sides of the input using the trim function, convert the input to lowercase using the toLowerCase function to get a make a uniform search.

const trimVal = val.trim().toLowerCase();

Perhaps, we can check if the user is submitting empty data before you request the API using the fetch API.

if (trimVal.length > 0) {
    const api = `https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info&inprop=url&utf8=&format=json&origin=*&srlimit=20&srsearch=${trimVal}`;
    const response = await fetch(api);
    if (!response.ok) {
       throw Error(response.statusText)
    }
    return await response.json();
}

Notice in our API endpoint, we interpolated the trimVal as a value to the srsearch parameter. This is because the srsearch parameter is responsible for searching for content matching its value. We check for the status of the request and throw an error when something goes wrong. Your fetchData function should look look this.

async function fetchData(val) {
    const trimVal = val.trim().toLowerCase();
    if (trimVal.length > 0) {
        const api = `https://en.wikipedia.org/w/api.php?action=quer             y&list=search&prop=info&inprop=url&utf8=&format=json&origin             =*&srlimit=20&srsearch=${trimVal}`;
        const response = await fetch(api);
        if (!response.ok) {
            throw Error(response.statusText)
        }
        return await response.json();
    }
}

Next, we create a method to get the inputs from users. This function will collect the inputs from the users, and then call the fetchData we created earlier. The fetchData takes the value from the input as a parameter. We await the response from the API request and save the value to our state.

    async function handleSearch(e) {
        const { value } = e.target;
        setResult({ result: await fetchData(value) })
    }

Finally, we need to listen to incoming events in our input field. When a user types a word, the handleSeach method will be called, which then requests the API for that particular word. We achieved this by listening to a keyUp event. Relace the input field with the code below.

<input type="text" className="search" onKeyUp={handleSearch} />

Open Source Session Replay

OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.

replayer.png

Start enjoying your debugging experience - start using OpenReplay for free.

Display Results

Let’s display the search results to the user. We will create a separate component for the result, which you can find in the encyclopedia/components/Word.jsx. First, open encyclopedia/components/Search.jsx component, and send the search result to the Word component. We will check if the search returned a result before, sending the result to the Word component. This is a good practice to avoid errors when no search result is returned. Now, locate the division commented {/* Search result component */}, then add this code to it.

<ul>
    {result.result && result.result.query.search.map(data => <Word key={data.id} data={data} />)}
 </ul>

Next, create a functional component Word component, which will be receiving the search results as props from the Search component.

function Word(props) {
  return (
    <div className="listData">
    </div>
  )
}
export default Word;

Next, we need to get the listData element and append the search results to it.

const searchList = document.querySelector(".listData");

When a request is made to the Wikipedia API, it returns a response like the one on the screenshot below.

Search Api Result Format

Perhaps, some of the search results from the API return a text with some HTML tags.

"Vitamin <span class="searchmatch">D</span> is a group of fat-soluble secosteroids responsible for increasing intestinal absorption of calcium, magnesium, and phosphate, and many other"

So we need a way to parse the HTML tags and display them to the listData node. This is where the insertAdjacentHTML method comes to play. We use the insertAdjacentHTML method to parse the text from the search result and display it on the listData node. Then we get the title and the snippet, which are the searched word and the meaning respectively, we then display them to the user.

searchList && searchList.insertAdjacentHTML("afterbegin",
    `<li>
        <h4>${props.data.title}</h4>
        ${props.data.snippet}
    </li>`);

Finally, let’s move to our browser, go to http://localhost:3000/ and search for a word.

Application search result

You can get the full project from Gitbub, the complete code is in the complateVersion branch.

Conclusion

In this tutorial, we learned how to build an encyclopedia using the React and Wikipedia Search API. We had an overview of what Wikipedia search API is all about and its implementation in our application. If you have any questions, feel free to reach out on Twitter.