How to make a random cat image generator with React and Cat API
If you prefer video format then I have already made a video on YT:
Prerequisites:
Node.js installed in your system (PC)
VScode (or any other code editor) installed
Getting the base right 🚩 :
- Open CMD (terminal if working on Linux or Mac)
- Type the following command replacing the angle brackets with its content to the name you want to give to your site
npx create-react-app <your-app-name>
3. After the installation process type:
cd <your-app-name>
code .
If [code . ] command doesn't work then open the folder of your react app manually using your own preferred code editor
Working with the code 👩💻 :
- Navigate to the App.js file
- Delete everything inside the div with className = “App”
- Create two new files (components) inside the src folder and name them ‘Header.js’ and ‘Cat.js’
- In the Header.js file add the following code
This is the non-important part of the app we just define some basic things over here
5.In the Cat.js file add the following code
Explanation:
Here, we create a state variable called url and set it to an empty string. Then we create a function called fetch_data in which we determine the logic to fetch the data from the Cat API. Everything we do inside the fetch thing is just to fetch and then convert the response object to JSON. If there were any errors while fetching we show them else we just set the url state variable to jsonRes[0].url because we get the response in a particular format like:
[{"breeds":[],"id":"lm","url":"https://cdn2.thecatapi.com/images/lm.jpg","width":560,"height":420}]
It is an array of objects(rather an array of only one object) and we just gain access to its image url.
Finally, we render the image and button. If there is no image url specified then there will be nothing and when we press the button, we run the fetch_data function and store the image url into url state variable which we use as the src for the image.
Your main part is over now. A bit of styling would help to make it look at least a bit more presentable.
6. Add both the components into App.js
Styling ✨ :
- Navigate to App.css file
- Add the following things ( Do not change the existing styling):
Your random cat image generator is done! Type npm start in the terminal and see the results
If you want to see more such content from me, then do subscribe to my channel: