How to Create a React Live Search Component with Images and Custom HTML in Laravel

I think everybody is familiar with the concept of Ajax Live Search ie a Search box that gives the suggestions that are updated as per the string entered by the user. These suggestions come in real-time from the connected database. Every day we are seeing it when we are using Google or YouTube where we get related results in the drop-down menu associated with input we type in the search field. Basically, everybody uses 3rd party javascript libraries to create Ajax Live Search. The Jquery UI Autocomplete and Twitter Typeahead are the most popular one. But one problem I usually face with these libraries is they are extremely difficult to customize according to your needs. You need to follow their rules and limitations. That is why I created a very simple custom Ajax Live Search with custom HTML and Images by using only Vue.js and Vanilla Javascript with almost all same functionality that Jquery UI Autocomplete and Twitter Typeahead offers.

In this tutorial, I will show you how to make a simple React Live search Component with Images and Custom HTML and implement it in your Laravel projects. This component is very simple to maintain and can even use outside of your Laravel project. I will be using Laravel as backend in this tutorial, But you can use anything as the only thing you really require is well-formatted JSON search result. Besides, React I will also use Axiosfor making HTTP API requests and Lodashfor easily adding extra functionality in javascript. These are already included in Laravel if you are using Laravel mix starting from Laravel 5.4 and above.

If you are completely new to React or ES6 terminologies then I really suggest you to learn the basics before continuing this tutorial as React is a little more complicated than jQuery or Vue.js. If you love the simplicity and doesn't care about complex frameworks like React then I suggest you to check out my simplest version this tutorial using Vue.js by visiting the following link,

Let's Start Coding

First thing is to include React in our application. In the case of Laravel, you can easily include React using Laravel Mix.

1) Setup Laravel Mix

Laravel Mix provides a fluent API for defining Webpack build steps for your Laravel application using several common CSS and JavaScript pre-processors. All you need to do is install Nodejs and NPM in your development system and run

npm install

to install all javascript dependencies in your application. By default jQuery, Bootstrap, Vuejs, Axios and Lodash are already included in this setup. Now just run

npm run watch

to compile your assets. Don't forget to include app.css and app.js files in the public folders to your Laravel View Layouts.

Now there is a little twist. If you are not using Vue.js in your laravel projects then you can replace the Vue.js with React by just running the following commands.

php artisan preset react

This command will swap out the Vue scaffolding with React scaffolding. The default Mix configuration, components, and all other related files will be updated accordingly. Don't forget to run npm install and npm run watch after executing this command. Please note that this will work only in Laravel 5.5 and above.

Now if you want to include React to an existing Laravel project (5.4 and above) without removing Vue.js then you can follow below instructions to include React without disrupting your old Vue components.

The showReactSearch method is used to just show our view page and getReactSearch does the actual database querying and fetching of the result. Although you can directly return $posts after the database querying I am not doing that because in order to fetch post images I need to call an external Helper function. So I am using map method in Laravel to run over the original collection and then to create a new associative array with only fields I needed. After that, I just return that collection as Laravel will automatically convert it to JSON when returning it. If you are wondering about catch_first_image custom helper function and how to create it you can refer the following Link.

Note: Both controller and routes parts will exclusively depend on your projects you are working on. They are unnecessary in this tutorial as only this they do is give some response data. I just added them only for reference purpose.

4) Setup your Laravel View

Now let's create demo/reactsearch.blade.php file to include our React Component. The complete code of this file is given below.

Don't forget to include your bundled js file at bottom of your view file. Remember you will see some fancy class names but don't worry about it as CSS and HTML parts changes according to your requirements. I just used Material design lite and Bootstrap 3 in creating ShareurCodes.

4) Create React Components

Before you create your react components, don't forget to include them in your resourses/assets/js/app.js or in the resourses/assets/js/react.js file (If you are including React alongside with Vue and want to bundle it separately) as below.

// React Components
require('./components/ReactSearch');

Now Let's create our primary React Component. The complete code for the component/ReactSearch.js file is given below.

As you can see I am registering 3 javascript Event listeners when the component is mounted. The resize Event Listener is registered to make our app listen to every browser window resize event so that we can recalculate the search widget's width thus make our application more responsive. The clickEvent Listener is registered to make our component listen to every HTML body's click event so that we can hide our search popup widget when someone clicks on outside the search input field.

Note: I also registered keydown Event Listener even though I am also listening to keyup Event because I need to prevent cursor movement when I am pressing up and down arrow keys inside the search box. If I only used Keyup Event then I cannot prevent it because the event already triggered. But I also need to use Keyup Event since Keydown event is one character behind when updating the search state.

Note: If you are using this component outside Laravel projects don't forget to globally include both Axios and Lodash.

The keyUpEvent will trigger handleSearch method when the input field changes. Inside this Method, I am checking whether it is a arrows keys and enter key press or not because we will be calling separate methods when they pressed. _.includes is a Lodash exclusive helper method which helps us to easily check whether a required value is in the array.

I am using _.debounce helper method of Lodash to delay the getPosts method call by 500 milliseconds thus prevent unwanted frequent ajax call to the server on every key press. The getPosts method is used to send ajax post request to the server and to fetch its result. I am using Axios for doing that. Since the result is already in JSON format, The React will automatically parse it to Javascript Object Array.

Now Let's create our nested Functional Stateless React Component. The complete code for the component/List.js file is given below.

We will be passing out individual post as a prop to this component. This component just displays post title and image inside a li tags. Beside post, we also pass count and index as props to this component. This is used to activate active class based on our selection. The selectPost method increment or decrement count state by one when we press up or down arrow in the search box. It also triggers click event to link associated with each List component.

Now before winding up Let's add some styling to our demo application. The complete code for sass/components/react-search.scss file is given below.

Feel free to customize it according to your taste and application. I just customize it according to my demo app look and feel. One important thing is your widget position should be absolute so that it floats over other elements.

The output image of above program is given below.

The Demo

If anybody found this method difficult and time taking then feel free to use jQuery UI Autocomplete and Twitter Typeahead. I already made a simple tutorial about jQuery UI Autocomplete with Images and Custom HTML in Laravel and Twitter Typeahead integration in Laravel for you guys and feel free to check them by visiting following links.