Tech enthu | YouTube| Blogger |Curious
Easy guide to filling your life with (more) internet cats by making a random cat image generator with React and Cat API. If you prefer video format then I have already made a video on YT:
Node.js installed in your system (PC)
VScode (or any other code editor) installed
1.Open CMD (terminal if working on Linux or Mac)
2.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:
If [code . ] command doesn't work then open the folder of your react app manually using your own preferred code editor
1. Navigate to the App.js file
2. Delete everything inside the div with className = “App”
3. Create two new files (components) inside the src folder and name them ‘Header.js’ and ‘Cat.js’
4.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
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.url because we get the response in a particular format like:
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
1. Navigate to App.css file
2. 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: https://www.youtube.com/channel/UCv2hTdClW8560n89OZ6cazA?view_as=subscriber
Create your free account to unlock your custom reading experience.