Make a Search Bar with React (with API Calls) | Beginners Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone so today we'll be learning how to make a search bar in react so you can enter into the input field over here and you can type in a few letters and you can see that the search bar fetches some data from an API and renders data relevant to your search query so this is an amazing project if you're a beginner because not only will we be making a react project from scratch where we go through the HTML CSS and JavaScript but we'll also be learning how to fetch data from an API and render it onto the front end so without much further Ado let's get started now I'm assuming you have npm installed on your machine before we begin so we'll go to our IDE of choice and open up the ID wherever you want to start the project and we'll open up the terminal and now usually when you start react projects you might have used something called create react app but today we'll be using something called wheat it's a lot more lightweight and it's a lot faster than create react app so that's what we'll be going with today so to get started with wheat what you'll have to do is write down npm create wheat at latest and now this should take us through the entire procedure of setting up our project so we'll name the project react search bar and then you can see it has a lot of options for many JavaScript Frameworks but we'll choose react and then today we'll be going with JavaScript but you can choose typescript if you want and if you can see here that it's created our entire project and it's also given us some commands we have to run to get started so let's do CD react search bar which takes us into the directory in our terminal then we run npm install to install the relevant dependencies and then once that's done we'll install another dependency which we need for our project which is npm installed react Dash icons we'll need this for some icons we'll be using in our project and now to start our project we'll just run npm run Dev and this should get our project running and as you can see at localhost 5173 we can see our project so let's refresh in our browser over here and you can see we have a simple landing page so now Veet has created loads of files for us but we don't need many of them so we'll go to the left hand side over here and begin cleaning up stuff so first of all you can delete this public folder over here and then you can open the SRC folder and go into app.jsx and you can basically delete everything inside the main div you can also delete this state over here and you can delete this import of the react logo and that's it for this file you can go into app.css and delete all the styling over here as well and save both of these files we can also go into index.css and delete all the styling here as well and then go into app.jsx and just write hello world and as you can see the page is being refreshed on the right hand side automatically whenever we save our files so to begin with adding the elements we'll create a div which will contain both our search bar and the results so we'll create the div and we'll give it a class name of search bar container and save that within that we'll create a div which will represent the search bar and then another div which will represent the search results these are just placeholders and will create the actual components later on but to begin with let's add some styling to this page so it looks a bit nicer so we'll go into app.css and begin by adding some styling to our app component so we'll Target it by saying dot app we'll give it a background color of Triple E and save that as you can see it has a grayish background here we'll give it a height of 100 percent of the viewport height and a width of a hundred percent of the viewport width now you'll see there's a white border around this component so we'll go into index.css and basically say that for the entire page by using this asterisks we should add these following properties so we'll Begin by adding a box sizing of Border box we'll see the default margin on each component should be 0 pixels and the default padding on each component should also be 0 pixels and save that and now you see that the app component fills up the entire page then we'll go back into app.css and we'll add some styling for our search bar container it's a search bar container we'll give it a padding on the top of 20 times the viewport height so that it moves down a little bit we'll give it a width of 40 of the parent component and then we'll move it to the center by saying margin Auto we'll make it display Flex give the flex direction to be column align the items to the center of the column and then we'll give a minimum width 200 pixels this is so that if the width of the page decreases below 200 pixels the component doesn't decrease in size so now that we have the app set up we'll go into creating the search bar component so for that we'll go into the SRC folder and create a new folder called components we'll create a new file for our search bar component and say search bar.jsx make sure to make it a jsx file because wheat doesn't like JS files it has to be jsx um now we'll create uh the functional component for this so I have an extension where you can just write rafc and it creates the boilerplate code for that so now we have a search bar component and then we can go into app.jsx and remove this line over here and just say search bar and it should automatically import it like so as you can see it still shows the same content so we're going to search bar.jsx and start adding some elements in here so we want the outside to be a div and we want to give it a class name of input wrapper and this will contain two things the search icon as well as the input which we'll take in the text so to add the icon we will go to the top and we will say import f a search from react icons slash fa this is the package which we installed earlier via npm now we'll go back into the component and we'll add it by writing on fa search and then closing this tag we'll also give it an ID of search icon so that we can add some styling to it later and if we save that on the right hand side we can see that there's a search icon and then below this we want to add an input which will take in the text and we'll give it a placeholder which will say type to search and that's the initial markup that we have now let's add some styling to this and then we'll come back to this jsx file for adding the functionality so to do that we'll create another file over here called searchbar.css we'll go back into the jsx and we need to import it so we'll say import dot slash search bar.css now we go back into searchbar.css and this is where we add the styling so firstly we want to Target the input wrapper which is the div around the search icon as well as the input so we say dot input wrapper we'll give it a background color of white and now you can see what the div looks like you can see a slight white background color behind this search element we'll give it a width of a hundred percent so it takes up the entire width of its parent we'll give it a bottle radius of 10 pixels so it's a bit more rounded we'll give it a height of 2.5 REM so it's a bit uh taller we'll give it a padding horizontally by saying zero vertical padding and 15 pixels horizontal padding we'll add a shadow to it so it's easier to see so we'll say box shadow and 0 pixels offsets on the X and Y and an 8 pixel blur and a color of DDD we'll save that I can see it has a slight shadow then we'll say display Flex and align items to the center so now you can see it's vertically aligned all the elements inside it now we need to add some styling to the input element itself so we'll say input we'll give it a background color of transparent we'll remove any border that it has we'll give it a height of 100 percent of its parent we'll change the font size to be 1.25 gram we'll make the width a hundred percent of its parent and we'll give it a margin on the left hand side of 5 pixels so it's a bit more spaced apart from the search icon um now so the styling looks good but if you click onto the element we see we have a outline over here and we want to remove that so to Target that we'll say input and whenever it's focused we want the outline to be none and now you can see there's no outline when you focus on the input element and then lastly we want to give a little bit of color to the search icon so we'll say hash search icon since it's an ID and we'll say color and we'll give it a color of royal blue and we save that and we can see that we have the search bar over here with the correct styling supplied now let's go back into the jsx file to add some functionality the first thing we want to do is to be able to figure out what the user has entered and for that we need the use State Hook from react so we'll get the use State hook and you can see that you can type in any text right now but we want to store this into a stateful variable so we'll come into the component over here and we'll say const input which is the variable that we'll be taking a look at set input which can be used to change what the variable's value is and we say use State and give it an initial value of an empty string now we'll come into the input element over here and we'll say that the value should be whatever the value of the input variable is and we'll say that on change whenever the user changes the value inside this taken the event and set the input variable to the value inside this input element by e.target.value and we can see over here that the typing still works but now it should be stored inside the input variable next what we want to do is whenever the user inputs some text we want to fetch data from an external API so for that we'll create another function inside this component which will be called const Fetch data this will take in some value which is the text to search for and over here we'll have to make a call to the relevant API so the API we'll be calling is called Json placeholder it's a very cool service which allows you to make fake API calls to this URL and it sends you some mock data so we'll be making a request to the user's endpoint so we'll go back into our code and we'll use the fetch API for this so This should take care of fetching data from an external API so we'll say https forward slash Json placeholder Dot type ecode.com users now this should make an uh make a request to the API but we need to call this function whenever the text changes in our search bar so instead of having uh the on change be just the set input we'll create another function which will be called const handle change this will take in a value and the first thing it'll do is is set the input variable to the given value which is the same as what we're doing over here and then it will also pass in the value to the fetch data function and this will make a request to the relevant API now we'll come down here and instead of doing set input we'll change this to handle change and whenever we change the text now it will make a request to the fetch data API without going into too many details of asynchronous JavaScript this fetch function is asynchronous so whenever you have an asynchronous function which returns a value later on in time you have to chain a DOT then function onto it which awaits for this result and then performs actions on it then we have to convert this response into the Json format which can be read by JavaScript so we'll say response dot Json we can chain another dot then onto that and we get back the Json value and what we can do is we can just console.blog the Json value that we get back and save that so let's go back to our app and open the dev tools by entering command option I and let's enter some text and we can see that we get back in Array over here and each array element is an object with an address company email and the name which we care about the most so now that we're done with fetching the data we only want to render the data which matches the text we have inside our input element so we'll add that functionality over here after we get back the Json data so what we want to do is filter the Json data and store it into a variable called results so we'll say results is equal to Json and we'll be using a function an array function called filter and this will basically go through each element inside our array and taken the user at the specific index and what we want to do is return true if it matches the text inside our input element and return false if it doesn't match it so we'll return first we'll check if the if the current user exists at the current index then we'll check if user has a name and then we'll check if the user's name converted to lowercase includes the value entered into our search field and we'll go ahead and save that and then we want to log this out so we'll say console.log results and then we'll refresh our page and then enter some text and we see there's only nine elements if we type in more text it keeps getting narrowed down until we only have one element which is Lian which matches our text now if we go ahead and delete every element you will see that we have 10 elements over here but the thing is if the input field is empty we don't want to render anything so over here in the filter function we'll also check if there's a value given by the user at all and if the value is empty then we won't render anything so if we type in l we'll get back nine results but if there's nothing we have an empty array so nothing will get rendered in the search results uh something I would like to point out here is that by getting data from the API again and again and by filtering it on the front-end side but usually what would happen is that you would send this value back to your back end via the URL over here or in the body of the request and you will only get back the relevant data so you wouldn't need to be filtering on the front-end side but for the sake of this project we're just filtering on the front-end side so now that we're able to get back the relevant data from the API and log it out we need to show it to the user via the UI so to do that we'll go back into app.jsx so what we want to do over here is create another stateful variable which will contain the results we've gotten back from the API because we want to be able to modify this array using the search bar and we want to send it into our search results component so it can render it out so we'll go to the top over here and we'll say const results which is the variable and set results which can modify this variable is equal to use State and we'll set it to an empty array initially now we want search bar to be responsible for modifying this array so we'll pass it in as a prop so we'll say set results is equal to the set results function we have over here then we go into search bar and we take it in as a prop by opening the braces over here and saying set results once we have that we no longer need to console.log the results we can just say set results and pass in the results variable we have over here now whenever the input gets changed it will fetch the data from the API filter it based on the text in the input and then set the results variable to whatever we get back which will be stored in this variable over here and since it's being stored over here we want to pass it into our search results component and render that out so instead of having this placeholder over here we'll create a new component inside our components folder so let's go over here and create a new component and we will call it search results list Dot jsx again do rafc to create the component and here it is we'll come back over here and remove this placeholder and just say search results list it's Auto imported and then we close the stack and then pass this results variable as a prop into this so now let's go back into the search results list component and add the markup so we want the outer div to have a class name of results Dash list and we want some divs inside it which will contain the list elements so we'll just create some placeholders for now so we'll say a B and C now you can see it being rendered out over here so let's add some styling to our list so we'll create another file called search results list dot CSS and we'll import it over here by saying import dot slash search results list not CSS now we'll go into the CSS and add the styling so we'll Target the results list div we'll say it should be a hundred percent width of its parent we'll give it a background color of white will display it as a flex but the flex direction should be column we'll also give it a box Shadow so it's a bit easier to see so the Box shadow pixel zero pixel 8 pixel blur and a color of DDD we'll give it a border radius of 10 pixels we'll give it a margin on the top of one Rams to space it a bit out from the input we'll give it a Max height of 300 pixels um and then whenever some whenever we have more elements than the maximum height we'll say overflow Y and scroll so by doing this um let me show you an example of why so if we have loads of elements like this instead of increasing in length forever there's a maximum height it goes to and then we can scroll through the results now that we're done with the styling let's add some functionality so we'll remove all the placeholders over here that we have and instead taking the results as the props that are being passed down to it and now what we want to do is that we want to go through each result and map the value in each result to a new div so we'll add some traces so we can add code in between the markup we'll see results dot map so this will go through each element inside the results array and map it to a new component so we'll take in the result at the given index we'll take the index as well that we're currently at and we'll use an arrow function and we'll say return for now we'll just do a div we'll use curly braces here and we'll say result dot name is what should be rendered and we'll also give it a key because whenever you're creating a for Loop like this every element you create should have a key and now when we go to our UI and we add in some text it renders out whichever users match our input now The Styling isn't looking that great so instead of having each result as a div we'll create a new component to represent each result so we'll go back into the components folder and create a new component called search result so search result Dot jsx again do rafc to create the component we'll take in the result it has to render as a prop and between this div tag we'll just say render out the relevant result and then we'll go back into the search results list instead of having this div over here we'll return a search result component to it we'll pass the result variable so result is equal to result and as before we'll give it a key of the current ID and we're getting an error over here because instead of passing the result we have to pass in the result dot name which is the name of the current user at the specific index and now it should work the same so let's go and add the styling to the search result component so we'll create a new CSS file by saying search a result dot CSS and we'll import it into the search result component by saying import dot slash search result.css to the div We'll add a new class name which will be called search Dash result and then we'll go into the CSS file and Target it by saying search Dash result and all we'll do is add some padding to it so add in 10 pixels and 20 pixels let's search for something and you can see that it looks a lot better and what we want to do is that whenever we hover over an element we want to highlight it so we'll say dot search result and we'll say hover and whenever we do that we want to change the background color so we'll set a background color of e f e f e f let's save that and refresh the page and let's type in l and whenever we hover over an element it gets highlighted and we can also scroll another thing you'll notice is that the font inside this element is in Sans serif it's Times New Roman so we'll go back into index.css and inside this asterisk just say font family and set it to helvetica and if that's not found apply any Sans serif font let's save that and it looks a lot better now lastly what we want to do is detect whenever an element inside our list is clicked so we'll go back into search result.jsx and add in an on click so we'll say on click and get the click event and then just make an alert dialog which says you clicked on and then by string interpolation we can pass in the result which was clicked on so alert you clicked on given result let's save that and refresh and type in l you can highlight the element that you're hovering over click on it it says you clicked on object object and that's again because we're passing a result instead of result.name so let's just fix that result.name let's save it refresh type in something again and it shows the name that was clicked on so that's about it for the search bar component if you want to take a look at the code the link for the GitHub repo will be given in the description down below if you like this video do like comment and subscribe and if you have any suggestions for any other tutorials do let me know
Info
Channel: Code Complete
Views: 60,339
Rating: undefined out of 5
Keywords:
Id: sWVgMcz8Q44
Channel Id: undefined
Length: 27min 48sec (1668 seconds)
Published: Wed Feb 22 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.