Using APIs in React - Image Search Application | React and React Router Tutorial 2020

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome back to my channel in this lesson we are going to build this image search application in react so this project is basically a replacement for my recipe search project that I created about a year ago unfortunately the API I used in that project which was food to fork has been shut down so a lot of people were messaging me saying that they could not follow along with that tutorial so I thought it would be a good idea to create something similar but using a different API so before we get started let me just walk you through the project and show you how it works so what we have here is a blank page for starters and this page has a form and an input and in here we can type anything to look for images so if I type kittens I get these images back from the API that we using which is pixabay now we can click on any of these images and then it takes us to the image page using react router here we are going to credit the author and let people know that this image is the property of pixabay then if we press this home button we get taken back to the home page again using react router and then if it tried to submit an empty form we get this nice little error message right so for this project I am going to assume that you are comfortable working with JavaScript react and react router if you are new to any of these technologies then check out my react for beginners video or react router for beginners video that I have on my channel alright so without any further ado let's get started right so first things first we are going to need a project folder so go ahead and open this link in your web browser github that come forward slash humza - Mirza and see getting this right is gonna be a challenge let's try again get talk.com forward slash humza - meza forward slash reacts - image - starter - files yeah there we go okay so once you're here go ahead and clone or download these files and once you have done that open the project in your terminal and press NPM install to install all the node modules that we need in order to make this project work once you've done that open this project in your code editor and for this lesson I'll be using Visual Studio code because let's be honest it's 2020 and if you don't use vs code then you are not say very cool person right so what we have here is a bunch of files that we're going to start with first up is the app dot J's file in our source folder and this file is going to act as the main wrapper component next up the index.js file and this is where we are importing all the good stuff like react bootstrap styles and then rendering this components onto the main index dot HTML file and then in this Styles folder we have three different style sheets actually for which I will go over once we start creating our components for now let's start building the basic structure of our app ok so first of all let's go ahead and launch this project and the web browser just so we can preview the changes in real time so go to your terminal and type NPM starts and this will launch the port 3000 on the computer and here is what we're going to start with just a simple component that reads this little message ok so now let's go ahead and explore the API that we are going to be working with so go to your web browser and in your google search type pixabay api and the first thing to pop up is going to be the one that we need so click that link and that should take you to pixel-based developer portal and once you're here scroll down to find your API key mine's right here but remember you have to first sign up or sign in to this website in order to work with their API service so be sure to do that first once you've done that come back to this page and you can find your API key right here so go ahead and copy this API key then go back to your an applet JS file creates a new constant calls API underscore key and then open a new string and paste your API key within the codes there we go now let's grab the URL that we need to make the request to so let's head back to the browser scroll down a little bit and that's the URL that we're going to make the requester right there and there's a sample API call so this link this one right there is going to respond with this JSON data that we see right here on the screen and this is what we're going to be using in order to grab the data for our projects so we have the image ID we have the URL that we're going to use in order to display the image and then we have the user ID as well as their user name so copy this URL from there actually let's do that in Reverse because otherwise it's going to select everything so copy this go back to your code editor and then here create a new constants calls URL but this time around open up a pair of PAP takes so we can launch a template literal and paste the URL right there and now instead of this API key let's get rid of it and then dynamically insert the API key constant that we have right here excellent so for the moment let's try and obtain the data back from the pixabay API later on we will set up a form that's going to fire off the request but for now all we care about is getting the JSON data to show up in the console so first things first let's turn this components into a class-based component because we're going to set up our own methods create our state and use a lifecycle methods and that is not possible within a functional components so I'm going to delete this app components completely ok and I'm gonna say class app extends react components and then within their create the render method and inside of it the return statement and within the return statement let's just return a div for now that reads up components press save let's check back in the web browser just to make sure that everything is working yes it is okay next let's create a method that's going to be responsible for making the request to this URL so just above this render method let's make a new methods calls handle get request and set it to equal and error function just like that and just a side notes I'm using the arrow function to avoid the this keyword binding confusion see in a traditional method like this so this one is a traditional method inside of a react components so in a traditional function like this one that this keyword binds itself to its parent method instead of its parent class and that can be useful in some cases but in this case we want that this keyword to always refer to our app components so the arrow function says that this keyword free meaning it does not bind itself to this keywords unless we explicitly tell it to do so so that's the cool thing about arrow functions so now let's go ahead and log a message to the console that reads something like working so let me just first convert it back to the air function okay now let's log a message the console that reads working excellence now we have no way to actually launch this method so one thing we can do is make use of the component lifecycle methods calls component did mount so just below this handle get request less you make use of the component did mount method and this method bronze just once and that is when the component first loads onto the web browser so in here we can call the this dot handle get request methods and fire it right away so the this keywords is referring to the app components and then in the app components we have a methods calls handle get requests so this is what's happening here okay now let's press save head back to the web browser and open up our console and we can see that behalf a message that reads working so remember this is going to show up just once when the component first mounts onto the web browser so when we reload the page that is when the component first loads onto the web browser and that is when this component did mount methods execute so we have the message showing up and it reads working and this is perfect let's move on ok so now that we have successfully created our methods let's try and make the web request to this URL so for that we're going to make use of two new JavaScript features the async await and the fetch API so the fetch API is actually a browser-based clients but it works in pretty much every modern web browser out there so it's safe to be used now the first thing that we have to do is make this handle get request methods asynchronous to do that we need to add the keywords async just before this pair of parentheses right there and now to actually make the get request let's get rid of this console first and creates a new constant calls request and set it to equal fetch and this fetch is a methods meaning we have to fire it off with a pair of parentheses and it takes one and only argument and that is the URL that we want to make the request to so in this case the URL is this constant right there so let's just refer it's right here like that's excellent now there is only one thing missing and that is to add the keywords await just before the fetch keyword right there so before we go any further I'll give you a brief overview of async await so the keywords async means we are going to make this function return I promise as well as resolve the promise automatically if it is successful and then we have the await keyword and this keywords only works in sight of an async function and its job is to make the function wait until the promise has been resolved and it has returned our results that's all this async await is it just simplifies promises and then we have the fetch methods and that is responsible for making the web request so as I mentioned the return value of this async await method is the result that is ready for us to work with so first of all we need to convert the data we get back to the JSON format so let's extract the return value which is the results from this request constant right there and store it into a new constant called response there we go and then set it to equal request and on this request a constant we can call a method which is just JSON so JSON followed by a pair of parentheses that's it now we have all the data we need and we can test this by logging this response constant to the console so let's say console dot log and then response now let's save the file and before we check our progress let me tell you that these are not the results that we're looking for okay so let's go back to the web browser open up the console so we can see that we have a promise and it's initial value is that it is waiting to be resolved and once it has been resolved as you can see on this property right here we can see that the response that we need is right here but that's not what we wants we don't want the entire promise object logging into the console what's happening here is that there is another promise waiting to be resolved when we try to convert the data to JSON format in this line so to fix that all we have to do add the keyword await before we fire off this json method on this request constant so here let's type or wait excellent so now if you save the file go back to the console we can see the data we want so if we crack open this object this is the data that we're looking for so what we need from here is this hits array and inside of this array there's a bunch of objects where we can extract the properties from and that's and that's exactly what we're looking for perfect now let's go back to the code editor and see what we're gonna do next so now that we have the data that we need let's try to simplify it by using this response constant so as we know everything is being stored into this response object so to access the properties let's drill down this object and grab this hits array okay so back in the text editor let's say response starts hits press save go back to the console and we can see that the hits array is being logged in and now let's go back to the code editor and try and do something a bit more interesting so right here at the top let's create a new state object so state equals to an object and inside of it let's create a new property called images and set its initial value to an empty array now inside of this gets handle request methods let's create a new line that's going to update the value of our state so right here let's say this dot set state and then we want to grab the images property and set its value to response dot hits excellent now let's log our state to the console so here let's say console dot log this dot state dot images and now let's head back to the console and we can see that the images array is being printed here perfect so let's crack open this and these are all the objects that we are going to use later on to extract the data okay so let's head back to the code editor and now we are finally ready to start adding new components but before we go any further let's do a little breakdown of what we have done so far so first things first you're imposing react from react and then we obtained the URL and the API key from pixel BAE's website and then we have a components called app and it is being rendered on to the web browser because we are importing it inside of our index.js file and here we are telling this file to render this component using the reject Dom render methods okay now back in our app your JS file we have our state and the state has a property called images and it's initial value is being set to an empty array after that we have our handle get request methods and inside of this method we are making a web request to this URL right there using the fetch API once we get the response back from the API we are updating our images state from an empty array to an array of several different objects that we receive from the API moving on we have the component did mount method which is a built-in method that comes inside of react components this method fires off automatically when the component first loads on the screen so inside of this method we are executing our handle get request methods and then we have the render methods that displays this little piece of text okay so that is the breakdown of what we have done so far let's move on right so now let's create a new component that's going to contain our form so inside of this source folder I'm going to create a new folder called image search okay and in here I'm going to create a new file called image search GS there we go as I'm also going to move this image search CSS file to this folder right there so the way we are going to structure this project is you are going to create a separate folder for each of the components and in that folder we are going to keep our component as well as the stylesheet for that particular components okay so now inside of this image search file let's first import react okay and then let's create a new functional component called image search and I'm gonna set it equal to an error function and inside of it I'm going to return a div that reads the message called image search excellent now let's go ahead and export this components right here at the bottom so export defaults image search there we go press save now let's head back to upload yes and in here let's go ahead and import the image search components of imports image search from and then it's image search and then image search there we go and now let's render the foam component inside of this app component right here so we can actually see it in the web browser so I'm going to get rid of this div okay and inside of its I'm going to create a new div and I'm going to say image search and I'm gonna make a component of it and press save now let's go back to the web browser and we can see the image search in all its glory okay so now let's go ahead and add some functionality to our image search components so back in this image search file inside of this div let's create a new form okay inside of this form let's create a new input and we're going to give this input a few attributes so first up let's set the also complete to off okay and then declare a name attribute and set its value to search value and remember this name attributes this is what we're going to use later on in order to grab the input value that the user types into the form okay and finally let's set the placeholder to search for images and then below this input let's create a new button and set its text to search excellent now let's save the file and see what we have in the web browser so we can see that we have our form there but the styling is a bit off but we will worry about styling once we have a fair bit of logic in place so I can see that I mistyped the bird images it's I am guestbook let's try to fix that first images there we go No why am i doing images there we go so now we need to find a way to trigger this handle get requests methods when we submit this form so how do we do that well the easy way to fix this is pass this handle get requests methods as props for this image search components so what we can do is I'm just going to copy this name because that's what I'm going to name this prop and I'm gonna set its value to this so remember this refers to the up components of there so this dots handle get requests that means that we will be able to access this methods using the props that are available inside of this image search components now to access the props we need to pass in the argument which is props so now here let's find out what's inside of this props so let's console.log this actually there's no this keywords now there's one thing to remember inside of a functional component that this keyword does not work I type that on purpose just to show you that it's a very common mistake to make you can get carried away and you can just type this keyword thinking that it will work but it won't because this keywords only only works in a class-based component here in this case that this keyword will not work so what we need to do is we need to say console dot log and then just the props now press save go back to the web browser and here we can see that the props are being locked in right there and then inside of this props you can see that there is a property calls handle get requests so we can access this method using props dot handle get requests press save go back to the console and there we can see that this is an asynchronous function and this is all the code that we basically wrote in our app the J's file okay and I'm also noticing that this should be div not DVI I'm not sure why I cannot spell today so now an easy way to hook this method up to this image search components is declare a property upon this form element right there so I'm going to cut this out this prop start handle get request method and I'm going to get rid of this console log and in here I'm going to use a built-in react attribute that we can use on formal events and that attribute is called on submit ok and I'm going to set its value to prop starts handle get request so now if I press save head back to the web browser nothing is going to change but what's happening now is we are extracting the handle get request method from the props object and then we are telling this component to trigger this method as soon as this form has been submitted and we are doing that by declaring an on submit attributes and remember this is not a custom attribute this is a built-in react attributes okay so how do we actually test that this is working I mean there is no way for us to know if it's actually working or not so first of all let's go back to this applet just components because at the moment this method is being fired off right away inside of this component it mount so I'm actually going to get rid of it because this was just to get the initial value of the results that we get back so I'm going to delete this component in mark methods entirely press save go back to the web browser just to make sure that there are no errors okay that's good so now this is where we need to make use of this the form elements right here but since we have set up this methods in a way that when this form gets submitted that is when this method is going to run so let's test this theory let's go back to the web browser and then press now keep your right there like just for a split second you will see a little line up here but then is going to disappear within half a second so as soon as I press this search button keep your eye right there did you see that little line so the results did appear for a little bit but they disappeared why because we went through a full page refresh now the default behavior of any form in HTML or even GSX is that they will trigger a full page refresh so what happens here is when we press the Search button the results they do get loaded but they disappeared right away because the page refreshes itself so we all we need to do to fix that is passing the event object as an argument to this handle get request method so we can call it event or Evi or e it honestly does not matter the main thing is that we need to access a property of this event argument or the event object and the property is called prevents defaults now the prevent default is actually another method and as the name suggests this is going to prevent a default behavior of a form now what's the default behavior the default behavior of the form is that if it refreshes the webpage as soon as the form gets submitted so what this line is going to do is it's going to make sure that the page does not get refreshed as soon as we submit the form so now if I press save head back to the web browser and press the Search button we can see that the results are there just as they were before so we are definitely getting there with our functionality let's keep moving ok so now let's take a moment to talk about this URL right there so if you take a closer look we can see that there's a parameter called Q and it's value is set to yellow flowers this means that it does not matter what we type in our form because every time we click search we are going to get the results for yellow flowers and we can even check that so let's go back to the web browser and then crack open one of these objects and if we try to open up this URL in a new tab we can see that it is a picture of a flower so now if we go back to the code editor and instead of this yellow flowers let's type something like banana okay press save go back to the web browser click search and now if you crack open one of these objects again go to this path and open up the URL we can see that there is a banana there so all these objects that you see rights here have some kind of a banana in them and no it's not the banana that you're thinking about but that's not the point the point is that what ever goes here inside of this URL right there in this place is what we're going to get back as the response so that means we can programmatically insert the value of our input inside of this URL right so let's first grab the input value okay so if you remember back in this image search components we gave this inputs a name attributes called search value so now back in AB DOJ's file below this either prevent defaults let's create a new constant called search term and set it to equal e dot target the elements dot search value dot value now this line is drilling down an object of different HTML attributes that are available to us and then it's going to find this name attribute whose value is search value and then it's going to grab a property attached to it which is this value property right here so now let's go ahead and log this search term constant to the console so right here let's say console dot log and then search term press save go back to the web browser and here let's type when we type frog press search and we can see the Frog is being logged into the console so now that we have the inputs value that means we are ready to use it inside of this URL right there for that's however we're going to have to cut this URL constant and paste it inside of this handle get request method so cut this out and then paste it's just below this search term constant and the reason we did that is because the value of this input is only going to be available inside of this handle get request methods this is something known as scope in JavaScript so we can definitely use this API key constant anywhere inside of this file because this API constant is in the global scope but the value of this input the one that we have here only lives inside of this handle get request methods that means we cannot use it outside of this methods okay because this is just how scoping works in JavaScript so now what we can do is since this is a template literal that means we can dynamically insert our own variables or constants so I'm going to get rid of this banana okay and in here I'm going to type in a dollar sign followed by a pair of curly braces and here I'm going to copy the search term and paste it right there so now let's go back to the console okay and now whatever we type in here should come back as a results when we make the API call okay so let's start with typing kitten okay press search and we can see that kitten is being walked in but now the main thing is are we actually getting this this kitten response back in the web I'm sorry and not in the web browser in the console so let's crack open when it's one of these objects and let's go to this link so go to this link and see what we get back and there we can see we have an adorable little kitten right there so that means everything is working right so now instead of logging everything to the console let's try to print some data on the web browsers window so for that we need to make use of our state so you see the only way for us to render the results to our UI is by grabbing what's inside our images array so for starters it is empty but as we submit the form and the state's value gets updated the images array starts to fill out and it provides us with the data that we can work with so to do that lets go to our render methods and just below this image search components let's open up a pair of curly braces because remember now we are working within GSX so to make use of pure JavaScript stuff you have to wrap it in a pair of curly braces so now we need a way to grab each and every item that is inside of this images array right there but the trouble is we cannot use a for loop or a for each loop because JSX does not allow that but the one thing we can do is we can make use of the array map method so before we go any further let's go ahead and try and explore this map methods in the browsers console so I'm back in my web browser console okay let me just zoom in a little bit and let's say we have an array of names so I will create an array called name so constant array equals and I'm gonna set it equal to a pair of square brackets and inside of it I will list my name which is Hamzah obviously I will list my cat's name and my cats called Cimber because he's a ginger cat so why not and my brother's name which is Hossam excellent so now we can map over each of the elements and manipulate them without changing the original array so to use the map method we start off with the name of the array which in this case is names and then we can say names dot map and this is a method and inside of it be passing a callback function and then this callback function also takes one argument and its value is set to each of the elements that are present in the original array so you can call this anything but I will call it name and now the return value of this entire map method is each of the elements that is present in the original array right there so now we can manipulate these elements without changing the original array and that's what we want to do so let's say that inside of this callback function I want to add my family name at the end of each of these names so I can say return name which is this argument so remember its value is each of these names right there so now I can say name plus and then I can add a shrink called Mirza and Mirza is my last name so now if I press ENTER we can see that there is an error and the error is that I should have named it names instead of an array so I'm just going to redo the whole process so constant I'm gonna set this value to names see it's very common to make this stupid errors I mean this should not have happened but this is part of being a developer you know this is part of writing code that you just make the silly mistakes every now and then so now I can just recycle the previous line that arose and now you can see that the space Mirza is being appended at the end of each of these elements in this array right there but the cool thing is that if we try to print the original names array so names we can see that it stays unchanged so I hope that explains method and I know it was a bit of a detour but I wanted to take time explaining it just in case there is JavaScript beginner watching this video okay so now let's refresh the page clear up the console and now let's head back to our code editor so here inside of these curly braces let's first make a check by saying this dot states don't images doc length is greater than zero and we are doing this because we don't want to map over an empty array so remember the initial length of this array is 0 because there is nothing inside of it until we make the API request in this methods so now we can make use of conditional rendering by using the and operator which is the and percent and percent symbol and now we can say this dot States the images dot map and then we passing the callback function and let's give this callback function the argument and I'm gonna call it image because this is referring to the individual image element that's inside of the array okay and now in here let's return a paragraph and inside of this paragraph we need to open up another pair of curly braces because now this is JSX so to make use of anything that's related to pure JavaScript we have to put in an other pair of curly braces so here we can say return image so remember this image is this image argument right there and now this image argument has access to everything that gets loaded inside of this images array so if you remember the images array gets filled with a bunch of different objects as soon as we submit the form so we can say that image and then dock tags and if you're wondering where this tags is coming from I will show you that's in a minutes so now let's press save head back to the web browser and search for dogs press search and now we can see that we all can sing something our printing to the screen and this is a great first step and if we crack open one of these objects we can see that there is the tax property right there okay so for each of the elements in the array which is from 0 to 19 we are getting everything printed onto the web browser and this is brilliant now let's talk about this warning it says each tiles in a list should have a unique key prop and this is actually react complaining that we should pass in a key prop to whatever we are returning inside of a map methods so what we're doing here is we're returning this paragraph so we should pass in a prop or in this case an attribute called key and the reason we need to do this is nothing to do with JavaScript or our UI is actually react react wants to know what kind of data we are trying to print onto the web browser and in case we ever need to manipulate the data react can easily use the key prop to change what we are trying to change okay so for now let's just say key and it needs to be a unique value okay it cannot be repetitive so to grab the key prop let's grab the image ID let's see if we can find the ID there we go so if you go back we can just say image dots ID so now if you press save head back to the web browser and search for dogs again we can see that the warning is gone and now we're getting everything printing on to the web browser excellent so now let's head back to the code editor and what we should really do is create a new components for this list of images that we are rendering because putting this logic inside of our main components render method is not a good idea so inside of this source folder let's create a new folder called image list and then inside of this folder let's create a new file image this George yes and let's also drag this image less CSS file to this image list folder excellent now in here do we need to make use of state no we don't so let's make it a functional component because we do not need to import all the functionality that comes with a class-based component so first of all let's import react from react and then I'm gonna create a new constant Scholz image list and I'm gonna set it equal to an arrow function and inside the words I'm going to excuse me just return a div and I'm gonna say image list and then let's export this image this component right here at the bottom so export default image list press save now back in Oviraptor JS file let's first import the image this component so imports actually let me just duplicate this line copy-paste and i'm gonna change this to image list there we go and then let's create a new instance of our image this components inside of our render methods so I'm actually going to delete this because we will make use of a map method inside of the image this component so I'm going to get rid of this completely and here I'm gonna say image list and I'm just going to make an instance of it so press save go back to the web browser just to make sure it is there yep there it is so now let's go back and see what we're gonna do next so now we need to somehow give our image this component the access to our images array that lives in the state object but the trouble is our state lives in the app component and our image this component lives in its own file so this seems like a case of passing data from one component to another and how do we pass data from one component to another we use props much like we did here with the image search component so we already have an instance of our imageless components now all we need to do is pass the images array and to do that I'm going to create a new prop called images and set it to equal this dot state dot images excellent now press save and back in our image this components we now have access to the images array we are the props object that we can pass in here as an argument so let's log this props object to the console and see what we get back so console dot log perhaps press save go back to the web browser and for starters the images array is empty because this is not gonna get filled up unless we make the API request so let's look for dogs again press search and now you can see we get an array of different objects so now back in the editor we can make use of this props object and we can map over this array and grab each of the elements that are present in the array okay so to do that I'm going to get rid of this image list components and in here I'm going to open up a pair of curly braces now in here I can say props and remember the name of the array is images or props or images that map and in here I'm going to call in passing the callback function and then I'm gonna pass in the image argument because this is going to store the value of each of the objects that live inside of the array so here I can return a new paragraph and inside of it I need to make use of some pure JavaScript stuff so to do that I have to pass in a pair of curly braces so now I can say image dot tags because remember that's the property that we're just grabbing for now and then if I press save head back to the web browser and then look for dogs again press search we can see that we do get a list of tags printing to the screen and this is brilliant but we still have a warning so what we need to do is pass in the key prop so I believe it was key set it to equal image dot ID press save go back to the web browser and look for dogs again press search and we get what we're looking for just a quick side notes this adding this image dot in front of every property that we're going to grab and we're going to grab a few more is a bit tedious I mean we can simplify it quite a bit using the JavaScript cs6 D structuring methods so to do that I can actually get rid of this image array once and for all I'm sorry the image argument and to destructor ik an object what you do is you pass in a pair of curly braces and from there you can grab all the properties that you want so for the moments we are using the ID property and the tags property so here I can just pass in ID and then tags and now I can just get rid of this images dot and then this is going to massively simplify over codes and it's a lot more cleaner to look at so now just to make sure that everything is still working let's go back to the web browser and look for kittens this time press search and we can see that we are still getting the same results as we were before the only difference is that our code is a lot more simple now okay right so this is all well and good but we don't really want to just print out a paragraph that shows a bunch of tags okay we actually want to structure our image list components in a way that it displays different images and then below that image there is a button tag that's going to ultimately take us to the individual image page so before we write down any complex structure let's first lay out the basic image tag and the button that we are going to display so I'm going to get rid of this paragraph tag once and for all and in here I'm going to open up a pair of parentheses and inside the words open up a new div and in here I'm going to reach and I missed AG so now where is the source gonna come from so let's go back to the web browser and then crack open one of these objects and this is actually what we want to grab in order to display the image so large image URL is the property that we need and now back in our code editor I'm going to replace this with a pair of curly braces and here I can actually get rid of these the tags for now because we're gonna need the ID and I'm going to paste the large image URL and then I'm gonna do the same here as well and now we need an old property as well so we can actually pass in the tags here so let's get the tags back and pass them right here just like so and then remember we also need a key prop and traditionally be passing the key prop to the most parents element that we are returning and in this case the most parent element is this div okay so we can pass in key and set its equal to ID now let's also create a new button and call it search now before we go any further let me tell you this is going to look absolutely ugly in the web browser because we don't have any styling in place so let's go back to the web browser and look for dogs press search and you can see that it's it's looking really bad because the images are are of different size and different height and different width so it's yeah it's just not looking too great I mean the dogs are absolutely adorable but we need to do a bit of work in order to improve the look of our project so now you're gonna have to watch me type quite a bit of HTML structure well it's not HTML it's just export you get the idea so I will fast forward this whole process so you don't have to watch me type but it's gonna be quite a bit of structure so you can either just copy and paste everything from the starter files to this components or you can just type it with me okay so let's do it okay so now this is the basic layout in place now all we need to do is import the style sheet that I've written for this component so I talked about these briefly earlier but essentially these are all the styles that are pre-written because this isn't a lesson on CSS so obviously I created this video assuming that you already know CSS so feel free to take a look at all these different style sheets that are there so this one is for image search component for the form which we will add later on and then this one here is for the image list so I've named these classes very appropriately so feel free to take a look at them and then you'll get that you'll get an idea of what's going on okay so right here let's import image this dot CSS press save go back to the web browser and now let's look for dogs press search and we can see that everything is looking pretty neat now so as I said I didn't want to waste your time by having you watch me you know type out all this structure because honestly it's not really anything to do with react so here's the structure right in front of you it starts from this div okay and then it goes all the way to the end of this div right there so feel free to type it out copy its do whatever and once you've done that come back to the video and we'll be good to go and I'll just notice that this should be view and not search so let's change that and while we're in the topic of styling let's also go back to our image search components but I promise this is not going to take as long so here we can we can improve the structure a little bit we can actually D structure this handle request methods so we don't have to type in their prob start keywords I mean it does not make a difference but it just looks better so here let's pass in a pair of curly braces and then passing the handle get request methods press save and now first of all let's import the style sheet for this components so style sheet image says dot CSS and that's it so if you go back to the web browser we can see our form looks much better and if you look for dogs again this is a much nicer looking application okay right so our application is looking great thank you very much for watching and I shall see you next time goodbye okay so now it's time to implement react router so what we want to do is create a new component that's going to display the individual image we click on and then show some of its details so first things first let's create a new folder and I'm going to call it image we you inside of this folder let's create a new file called image view yes and then drag this image view CSS file inside of its excellent now in here let's just lay out a basic functional component for now so imports react from react and then Const when I call its image view and set it to equal an error function and then inside of its return a div that reads image we you for now okay and now let's export this components right here at the bottom so export defaults image view perfect so now let's create another component that's going to act as our wrapper components and that is where we're going to make use of react browser so inside of this source folder let's go ahead and create a new file called router doc Jas and first things first we're going to import react from react and before we do anything else let's just lay out the basic the basic structure of the component so it's going to be a functional components calls router or Rooter depends where you are okay and I'm gonna set it equal to another function and in here for the moment let's say div call it router why do I keep typing the O as a capital okay export defaults and then rotor press save and then now this is what we want to render in our indexed or JS file instead of this app components because this is where we're going to import the app components and int here we're going to put in a bunch of react rot logic so now back in our index dot JS file let's replace this with router okay press save go back to the web browser and it says that router door just line four let's see what's happening there line number four oh we actually need to add the return key words my bad return and then router there we go now it should work so as I said in the beginning I am going to assume that you already know how to work with react router if you are new to it then feel free to check out my react router tutorial and if you already know how to work with react router just stay here with me okay so I already have the react grata dependency installs and this project is this one right there so we don't need to install anything with NPM so first things first I'm going to grab a few named exports from the react ratted on package so imports from react racism and the named expose our browser router switch and then its route so now this browser router is going to act as the main wrapper dev I mean it's not a div it's a basically a wrapper component so here we can say browser router ok and inside of it we need to wrap everything inside of a switch component just like so and then here we can declare our routes so for the for the first routes what we can do is we can give this one a path of the forward slash which is just the homepage and then the component that we want to show for this path is the app components but in order to do that we first need to import the app component so imports app from and then it's app there we go and then we need to create another path so let's say routes come on there we go and then the path is gonna be a little different because we want to throw in a cratering right at the end so this path is gonna be called forward slash image and then forward slash colon ID now this ID is going to get replaced by whatever goes in here we will talk about this in great detail later on but for now I just know that this is a replaceable variable okay anything can take place of it and now the component that we want to show for this path is image view and then we also need to import image for your component so impulse image view from and then we need to go to the image view folder and then grab the image view file excellent now one last thing that we need to do is give this initial path a value or an attribute in this case called exact and we need to do this because react router by default renders everything that matches the initial rector in this case the initial character is the forward slash and this forward slash is also present in our image path right there so what this is gonna do is it's going to render both of these components of on the same page and we don't want that we only want the app component to show up on our homepage and then we only want the image view component to show up on our forward slash image path okay so now if I press save go back to the web browser everything should still work as it was before so if I search for dogs press search we can see that everything is there now we need to find a way to make this button work so we need to set this up in a way that when we click it we get taken to this path and then this gets replaced with whatever image I T that exists inside of the objects okay okay so to achieve that functionality we need to go ahead and make changes to our image list file this one right there because this is the button that we're using to navigate to the individual image page so what we want to do is wrap this button inside of a component that comes with react router so what we need to do is import a named exports called react routes it's on and what we want to import is a component called link now this link act the same way as the anchor tag in flame HTML its job is to navigate from one position in the project to another so what we want to do now is cut this button out open up a link tag and then create a pair and inside of it paste the button but that's not all there is to it because technically it is a link but in order to make sure we get taken to the individual image we need to pass this opening link tag one attribute and that attribute is called - now normally you can make this work by saying that what path you want to go to once the button has impressed so we can say like go to this path or go to /m edge like that and then the ID but in this case we won't do pass it multiple values because we want to pass it a path which is obviously what's going to happen once we click the button and then we get taken to that path but we also want to pass it the stake value which is the image because remember the image states here is what we are working with so I talked about destructuring early on but what we're going to do in this case is we're not going to destructor anything here because we need to pass in the entire image object to one of those values that we're going to create here briefly so first of all let's get rid of this entire destructured element and replace that with image and now we also need to make changes here so we need to say image dots and then we also need to change that to image dot tags excellent so now in instead of passing in a string value to these two attributes we need to pass it two pairs of curly braces okay now the first property that we need to pass is called a path name if you remember the path name that we set up here was /m it's forward slash colon ID now back here in image list components this is the path that we want to pass in so instead of opening up a regular string we're going to open up a pair of back ticks to initiate a template literal and here the path is forward slash image and then forward slash now what do we want to insert in place of this ID so we want to add image ID here instead of this static : ID so if you remember I did say that this colon ID especially this colon means that anything after that is replaceable okay so what we can do is get rid of this and here let's say dollar sign curly brace and now we want to insert the image Isaiah and I just remembered we need to add the image prefix here as well so a master and this is actually what we can copy and paste right there okay and then the next property that we need to declare is called state okay and this is gonna be an object inside of it you can call it anything but I'm going to name the state's image okay and I'm gonna set its value to this image right there so just like so there we go now here we can use some cool es6 magic which implies that if there is an object and inside the object the name of the key and the values are the same then we can actually just leave it there like this okay so this is same as saying image is equal to image but if that was something different like if this was images or images but then we would have to type it as is but since this image and this image are the same words we can actually just leave it there like that it does not make a difference you can still type it that way it just simplifies your code to a fair degree so what we've done here is we have access to this image you know the object that gets stored inside of this image we have access to it inside of our image via components and the reason for that is that we have declared a property to a link that is linked to the button that takes us to the path name when it gets clicked so this is what is linking this component to this component and then through the state we have access to this image arguments okay this will make a lot more sense once we actually start building our image view components so let's go to our image view components and see what we can do there so here as I said we have access to all the objects that are inside of this image property we have access to it we are the props arguments okay and we can actually prove it so here we can say console.log props and then press save go back to the web browser and let's look for pizza press search and now when we click on this view you're going to get taken to that path of /m eight forward slash : IT and whatever ID of this images is going to replace that : ID so let's go let's press this button and you can see that the : ID is being replaced with the image ID but the interesting thing is that if we open up the console and these warnings that you see they're actually coming from some node module on line number 12350 seven so we don't have that many lines of code which means that this these warnings they've got nothing to do with that code that rip that we've written so we can actually ignore this message and we connect they ignore this message as well and now what we're left with is if we crack open this image view line number four because remember this is very logging or props I'll check to the console so let's open this object and see what we get back so the first property is the match property and this is the URL so we were starting off the forward slash image forward slash : ID this that was the starting point the next stop wants this once we actually visit the URL after pressing the button this ID gets replaced by the actual image as a so that's what link is so now we have another property called location inside of this location property we have a property called state and inside of the state we have an image property and if you look this is the exact same response that we were getting back in the original API response so as you can see we looked for pizza so if we check somewhere in the tags there's a pizza slice it's Holly and so I hope that this is starting to make sense now so we can actually make use of this state dot image property to display the data on our screen so to do that let's go back to our code editor and now to actually extract the properties what we have to do is drill down this image so it's going to be something like props location dot state and then dot image so let's go back to the and try to clean up our result for so props dot location dot state dot image press save and there we go I don't know why this morning's keep popping up ok so now this is the object that we can use I mean it's been massively simplified so all we need to do now is extract out some of the properties that live in here ok so let's go back to the code editor and lay out what we are trying to achieve so first of all obviously we need an image and inside of this div I'm going to get rid of this image view and I'm going to open up a new image tag and I'm going to set its source to its image dot and then large image URL and then I'm going to set its alt tag to image dots image got tags there we go so let's press save just to make sure that it is showing up and it's I mistyped it again what is wrong with me okay so image there we go let's go back to the web browser and it's still not working I wonder why because this should be prop start image and this should also be prop starts image press safe go back to the web browser and it's still not bloody working cannot read property large image URL of undefined and I know what this is what's happening here is we need to actually drill down the property like this so props dot location dot state dot image but this is going to get a bit ridiculous because we don't want to do this for every element that we have inside of our return statement I mean we have the image tag then we're gonna have a paragraph tag h4 tag a button and we don't really want to put this props dot image in front of each and every property this is going to get extremely messy so what we can do is right up there creates a new constant okay and this is another form of destructuring so what we can do is stay with me Const followed by a pair of curly braces and set it to equal props location upstate dot image now from within this property the image property we can extract whatever we need so obviously we need large image URL okay we need the tags and then we also need the username for the user and then the page URL that we can redirect our users to okay and one cool thing we can do here is we can give these properties of our own preferred name so I don't like that we have to use the large image URL property so we can declare our own name so to do that let's type in a colon and then set it to image now if we use this image anywhere inside of our file this is going to suggest that the value of this image is this large URL image right there so this basically is just a nickname for this property okay and I also want to set this to owner just like so there we go and everything else is good to go so now here instead of using this large image URL we can actually get rid of it just like that and we can also get rid of this props and then here we can just say tags so now if you press save go back to the web browser we can see that there is an image showing up and this is perfect okay now what else do we need well we also need a paragraph tag that lets people know that this is the copyrights of pixabay so let's creates a new paragraph tag and then we need to insert the HTML entity for the copyright symbol and that is the end % followed by the copy keywords and then a semicolon and here we can say pixabay let's go back to the web browser just to make sure it's there yep there it says and now next up we want to credit the author so let's go ahead and create a h4 right there and say credits and set it to equal a span inside of it less destroying the name of the owner so remember we can just use this word right there ona there we go let's indent this back so what do we need to do next well there's also a download button that users can use to get redirected to the page where they can download this image from so let's type in download colon and then a span inside of the span let's open up a an anchor tag and now the href of that is going to be this page URL right there so let's set it to equal page URL but we want this to open in a new tab like when the user clicks this link they should get redirected to it in a new tab so for that we can use the HTML target attribute and we can set it to equal underscore blank this is going to make sure that whenever user clicks this link they get taken to the link but the link opens in a new tab so our application remains open in the currents app but the new tab opens and that's where this link is going to be showing all the data that's supposed to be shown if that makes any sense okay so in here let's type go to download press save go back to the web browser and see if we have what we want so here we have the credit which is perfect and let's try and press this and see what happens so this does not appear to be working so let's go back to our code editor and this is because this needs to be within the anchor tag right there so let's go back and press this go to downloads and you can see we get taken to the relevant page and this is perfect and here we can download the files right so now we need to add a button on this imagery component that we can click and then we get taken back to the home page so to do that let's go back to our code editor and in here to add the button let's first import the link tag from react rotterdam so it's going to be a named exports from react rotted zone here we need to import the link components there we go press save and now just below this h4 let's open up a new button tag and inside of its a link tag and then let's give this an attribute of 2 and then set it to equal the home page or the base URL and then here we can say home so now let's go back to the web browser press home and then we get taken back to the home page so now the only thing that's missing is the error message when we press search so when we press search it does give us a default set of images and while this isn't a bad thing I mean it doesn't make much sense to just press search and then brick and then we get a bunch of images back it only makes sense for us to see the images when we actually type something in there so to do that let's go back to our app components right there and then here we can conditionally render this image list components so first of all let's cut this out and then open up a new set of curly braces in here we can first declare a new property called error in our state's error and for starters let's set its value to no and now inside of this handle get request methods let's first get rid of these two console logs because we don't need them and now here we need to make a check so first of all let's cut this line out and now we can check for the presence of our search term so obviously this is the user input so we can do something like we can make a check that's if this search term is present then we can go ahead and set the value of our state which is the images array and if this search term is not there then we can change the value of our error State so to put that in practice let's create an if statement so we can say that if there is no search term so this is going to be the boolean value so we can reverse this by using the exclamation mark right here in the beginning so this is going to flip the value so this is going to evaluate to false which means that the search term does not exist so this is saying that if there is no search term then what we want to do is we want to set the value of our error so this start set States and then the value of the error is please provide a value and then if that is not the case then we can go ahead and continue with updating our images array and in here what we can do is we can make a check that if the value of our error state is no that means there are no errors however if it is anything other than no that means there is an error so in that case what we can do is first of all let's cut this line outs and let's say this dot state error is not equal to no and now we're going to use something called a ternary operator so if you don't know what a ternary operator is stick with me and I'll show you so first of all type this out with me and then we'll go through it step-by-step so a question mark and then we're going to create a div okay and inside of this div I'm going to say this dot state the error and let's also give this div a style just some inline react styling and I'm gonna give it a color of FFF which is white and I'm gonna say text a line and set it to Center there we go so now what we need to do is add in a colon and here we're going to paste the line that we cut out so what's going on here is we are first making a check we're checking that if the value of the state is not equal to no then what we want to do is render out this div which reads the value of the state which in that case is going to be please provide a value and then this colon stands for else so this is essentially an if-else statements and what we're taking is if the value of the error is not equal to null then do this so this question mark refers to then clause else so this colon refers to the else clause so if none of this evaluates to true then do this so if this happens do this if it doesn't then colon do this so now if I press a go back to the web browser and try to submit an empty form we can say that we have an error that reads please provide a value and if you type something here let's say Berger press search and this does not appear to be working so let's go back and see what's going wrong and I know what's going wrong what we've done here is we have set the value of the state to please provides an error and this stays there because even if we do type in a search term there the value of the state remains the same because we are not changing it anywhere so even if we do type in a value this still evaluates to true because we are not resetting the value of the error in this state so in here what we can do is say error and set it back to No okay so C is this little things like this that do come up as a mistake I mean I could have just edited out this part but I just want to show you that this is the part and parcel of being a developer and it's perfectly normal to make mistakes like that okay so now let's go back to the web browser try to submit an empty form and it's working like we want it to and then if you press and then if it's happen Berger press search the error goes away and we get the images for the Berger and now if we click on one of these burgers we get taken to the page where all the good stuff is and then we can go home perfect so the only thing that's missing now from this application is the image view styling this right there I mean the image is too big these don't these don't look too bad what is the image that really needs some styling so I'm not going to bore you with all the styling parts because this is the bit that needs styling so what so what I'm gonna do is I'm going to quickly do all the styling and then I'm going to skip to the part where the styling is complete and then you can copy the whole structure by seeing what's on the screen or you can just go to the github repo and then copy the styling from there because honestly I don't want to bore you with it so I'll be back in a minute okay so this is the final structure of this component as you can see this would have taken quite a bit of time to get it right because there's quite a bit of structure there so what's happens here is I've imported the image we've CSS file which is this one right there and then what I've done is I've just added some bootstrap classes and then the classes that are supposed to be there that I've written in this file so now if you go back to our application let's first submit an empty form and now let's look for cats press search and if we opened one of these let's open this one because this is what my cat looks like like I said I have a ginger cat and this is exactly what he looks like so we can see that this is a much better styling I mean it's not perfect by any means but that will do okay so that's everything for this application and I hope you learned something from it and if you did then please drop me a like and subscribe to my channel and I'm actually trying to so the key words here is trying I'm trying to create a Redux tutorial and to be honest it is very hard to explain read X because Redux is a very complex library but I'm doing my best and I hope to get the read X tutorial outs within the next two weeks or so ok so again thank you for watching and I shall see you next time good bye
Info
Channel: HamScript
Views: 7,458
Rating: 4.9841895 out of 5
Keywords: javascript, react, react.js, js, react for beginners, web development, web design, web app, app, web applicaiton, API, js api, programming, html, css, react tutorial, javascript tutorial, react tutorial for beginners, api tutoria, react api tutorial, react-router, react router, router
Id: 3OolwmBExB0
Channel Id: undefined
Length: 82min 53sec (4973 seconds)
Published: Mon Jan 27 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.