Creating Web-App for fetching facts about Numbers using React And Axios From NumbersAPI.

Hey!!! My name is Nandit Shah. I am a student. I am writing my first blog about creating a web-app using react that get us the fact about the number we write in. It is small and structured project to clear up your basics nicely in react.

Preview of the web-app

NOTE : I Am not going to cover CSS part of this project you can download this from my git-hub link.

Click here to download all the files of my project.

In this Project we are going to use Numbers API. It is the API that give as fact about numbers ,dates ,years etc.

It is very fun API for creating projects for practice.

For learning more about axios click here

First of all we need to create react app. For that we have to run command npx create-react-app fact-web-app in command prompt or git bash or any terminal you use.

it will take some time to install. And after the installation we need to install one package called Axios command npm install axios. Axios is used for making request such as GET or POST on front-end without any help of back-end you can make request.

// for creating and installing react app in your pcnpx create-react-app <app-name>// For installing axios npm install axios// For Running the on the server npm start

These are the commands that we are going to use.

Now after installing we need to delete some of the files that we do not need today for our project

These are the files that we will delete.

  1. App.test.js
  2. logo.svg
  3. serviceWorker.js
  4. setUpTest.js

Now as our downloading and cleaning is completed we will start our project.

Now first we will focus on components that we are going to build for our project. There will be only two components that we are going to create. Both of them are card in which one card will give us fact about any random number (Either trivial or mathematical) and second will give use the fact about the number we have given in the text-box.

  1. First create two files in in component folder FactCard.js & FactCard.css.
import React from "react";import "./FactCard.css";function FactCard({ name, handleChange, onclick, fact }) {return (<div className="area"><h1>{name.toUpperCase()} Facts</h1><inputname={name}placeholder="Enter Any Number"className="inputNumber"type="number"onChange={handleChange}/><button className="getFactButton" onClick={onclick}>Get Fact</button><p className="factText">{fact}</p></div>);}export default FactCard;

2. Code explanation : -

In this code we have just returned our HTML component in single div. In that div we will use <input> tag to taking the input from the user and <button> tag for getting the fact using onClick event and <p> tag for displaying the fact that has been fetched by the axios through the API. Here we have destructured the props we have passed the the component from the App.js

Here we have passed 4 props.

{ name, handleChange, onclick, fact }
  1. name(For getting the name whether it is math fact or trivia fact).
  2. fact (Fact that is fetched from the API).
  3. onclick (This is the method that is passed as a prop for handling the button click)
  4. handleChange (This is the method that is passed as a prop for handling change in input field.)
  1. First create two files in in component folder RandomFactCard.js & RandomFactCard.css.
import React, { useState } from "react";import "./RandomFactCard.css";function RandomFactCard({ onclick, fact }) {const [type, setType] = useState("Math");const [styleMath, setStyleMath] = useState({margin: "10px",color: "blue",backgroundColor: "yellow",border: "3px solid red",borderRadius: "10px",});const [styleTrivia, setStyleTrivia] = useState({margin: "10px",color: "red",});// Foe handeling click in random cardfunction handleClick(event) {if (event.target.name == "math") {setType("Math");setStyleMath({margin: "10px",color: "blue",backgroundColor: "yellow",border: "3px solid red",borderRadius: "10px",});setStyleTrivia({margin: "10px",color: "red",});}if (event.target.name == "trivia") {setType("Trivia");setStyleTrivia({margin: "10px",color: "blue",backgroundColor: "yellow",border: "3px solid red",borderRadius: "10px",});setStyleMath({margin: "10px",color: "red",});}}return (<div className="randomFact"><h1>Random</h1><ul><li onClick={handleClick} style={styleMath}><a name="math">Math</a></li><li onClick={handleClick} style={styleTrivia}><a name="trivia">Trivia</a></li></ul><h2 className="type">Random {type} Fact</h2><button className="getFact" name={"R" + type} onClick={onclick}>Get Fact</button><p className="factText">{fact}</p></div>);}export default RandomFactCard;

2. Code explanation

Our return section is almost same as above component. But the main difference is that here there is no input section for giving input here we just have to select whether we want Math random fact or trivia fact. So there will be no input field instead we have used un-ordered list (<ul>) for giving two option(Math or trivia).

Here we have used three state variable

  1. type ( For displaying which type of fact we have selected and change its state by selection one of the option).
  2. styleMath ( This state variable will hold internal CSS for Math option and this will change its state whenever we will select Math option or Trivia option so it will give us idea which option is selected at that time we have selected default Math option. For example. in our project if we have selected math option it’s font-color, background-color and border will change and then if we will select trivia option then all the style properties of math option will become same as before and style properties of trivia will change).
  3. styleTrivia (This state variable will hold internal CSS for Trivia option and this will change its state whenever we will select Math option or Trivia option so it will give us idea which option is selected at that time we have selected default Math option )

Here we have passed two props in this component from the App.js file.

  1. onclick(It is the same that we have used in first component details will be discussed in App.js part below).
  2. fact(it is also same that we have used in first component).

Here in this component we have created one method called hanldeClick .This method will basically change the option selected.

function handleClick(event) {if (event.target.name == "math") {setType("Math");setStyleMath({margin: "10px",color: "blue",backgroundColor: "yellow",border: "3px solid red",borderRadius: "10px",});setStyleTrivia({margin: "10px",color: "red",});}if (event.target.name == "trivia") {setType("Trivia");setStyleTrivia({margin: "10px",color: "blue",backgroundColor: "yellow",border: "3px solid red",borderRadius: "10px",});setStyleMath({margin: "10px",color: "red",});}}

here this method will check using if condition and if we have selected math option then it will change state of the styleMath and styleTrivia variable appropriately so we will be able to see which option is selected.

So this is all about out component part we have created component we need now we just have to import all these component in App.js file and then using axios we have to fetch the data from the API.

import axios from "axios";import React from "react";import "./App.css";import FactCard from "./Components/FactCard";import RandomFactCard from "./Components/RandomFactCard";class App extends React.Component {state = {mathFact: "",triviaFact: "",randomFact: "",inputName: "",url: "",};//Method for creating URL according to the inputcreateUrl = (event) => {this.setState({ inputName: event.target.name });this.setState({url: `http://numbersapi.com/${event.target.value}/${event.target.name}`,});};// Method for fetching fact using axiosfetchFact = (event) => {console.log(event.target.name);if (event.target.name == "RMath") {axios.get("http://numbersapi.com/random/math").then((response) => {this.setState({ randomFact: response.data });}).catch((error) => {console.log(error);});} else if (event.target.name == "RTrivia") {axios.get("http://numbersapi.com/random/trivia").then((response) => {this.setState({ randomFact: response.data });}).catch((error) => {console.log(error);});} else {axios.get(this.state.url).then((response) => {if (this.state.inputName == "math") {const fact = response.data;console.log(response.data);this.setState({ mathFact: fact });} else if (this.state.inputName == "trivia") {const fact = response.data;console.log(response.data);this.setState({ triviaFact: fact });}}).catch((error) => {console.log(error);});}};render() {const { mathFact, triviaFact, randomFact } = this.state;return (<><div className="App"><RandomFactCard onclick={this.fetchFact} fact={randomFact} /><FactCardname="math"handleChange={this.createUrl}onclick={this.fetchFact}fact={mathFact}/><FactCardname="trivia"handleChange={this.createUrl}onclick={this.fetchFact}fact={triviaFact}/></div><footer><p>Here I have used<a href="http://numbersapi.com/#42" target="_blank">Numbers_API</a>for facts</p>Made With ❤️ By Nandit Shah</footer></>);}}export default App;

Code explanation

Now first we will import all the components and axios.

Now we will have to create state variable which will contain state of our whole App.

state = {mathFact: "",triviaFact: "",randomFact: "",inputName: "",url: "",};

We have used five state variable in this file.

  1. mathFact (This will change it’s state when we fetch mathematical fact from the API).
  2. triviaFact (This will change it’s state when we fetch trivia fact from the API).
  3. randomFact (This will change it’s state when we fetch random fact from the API).
  4. inputName (This Input name will change it’s state when ever we select any option for ex. if we select math fact then inputName will be “math” and if we choose trivia fact then inputName will change its state to “trivia”).
  5. url (This is the state variable that will hold the URL we are going to use for fetching the fact and it will change according to our options selected and value given into the input field).

Now we will focus on fetching the data from the API using axios and for that we need perfect URL so we will create two methods that will help use to fetch the fact from the API.

  1. createUrl — This method will help us to create appropriate URL.
createUrl = (event) => {this.setState({ inputName: event.target.name });this.setState({url: `http://numbersapi.com/${event.target.value}/${event.target.name}`,});};

This method will set the state of the inputName variable to the name of the input we have chosen so if we select factCard component of math facts then it will set the state of that variable to “math”. and then it will create URL by appending the value of input field and inputName.

so for example if input we have selected is “math” and value we have given is 12 then this method will returned URL will be http://numbersapi.com/12/math.

2. fetchFact — this method will fetch the data from the url given by the createUrl and give use the output in JSON format using axios.

fetchFact = (event) => {if (event.target.name == "RMath") {axios.get("http://numbersapi.com/random/math").then((response) => {this.setState({ randomFact: response.data });}).catch((error) => {console.log(error);});} else if (event.target.name == "RTrivia") {axios.get("http://numbersapi.com/random/trivia").then((response) => {this.setState({ randomFact: response.data });}).catch((error) => {console.log(error);});} else {axios.get(this.state.url).then((response) => {if (this.state.inputName == "math") {const fact = response.data;this.setState({ mathFact: fact });} else if (this.state.inputName == "trivia") {const fact = response.data;}}).catch((error) => {console.log(error);});}};

This method will first check if the input name is RMath(Random Math) or RTrivia(Random Trivia) then it will use axios and fetch the fact from the URL http://numbersapi.com/random/math or http://numbersapi.com/random/trivia as per the name. so this IF section and ELSEIF section will work for random facts.

Now for given input if we want to fetch the fact then this method will go to ELSE block and in that block axios will fetch the data from the URL state variable whose state is set by createUrl.

axios.get(url).then(function(response){// Do whatever you want with the response you receive from the API }).catch(function(err){//This section will only run if any error found while fetching the //data.console.log(err.message);
})

After fetching the data this method check if the if the inputName is “math” or “trivia” and if the name is math then it will change the state of mathFact variable and assign value of the fact that is received in the response.

Now we are almost finished we just have to use components that we have created.

<RandomFactCard onclick={this.fetchFact} fact={randomFact} /><FactCardname="math"handleChange={this.createUrl}onclick={this.fetchFact}fact={mathFact}/><FactCardname="trivia"handleChange={this.createUrl}onclick={this.fetchFact}fact={triviaFact}/>

The above code will be in return part of the App.js

In above code all things are self-explanatory so no need to repeat anything.

Hope you guys have enjoyed reading and creating project

Thank You for reading this blog and if you like this blog or if it become helpful you in any manner feel free to give a clap and share it with others.

Student | Web Developer | MERN Stack | Python | Deep learning