How to create a Simple Search Component in React?

Search Component is a vital part of most Web Applications, specifically when creating a Search Engine using React, you must have a dynamic and well-functioning search Component. Let’s go through the detailed steps to create a Simple Search Component in React, that will enhance the user experience of your application.

Steps to create a Search Component

Add a new file under src/components

Create a new file for the Search Component, and write the code below to create and export your search component.

const SearchBar = () => {

}

export default SearchBar;

You must export your component to use in other files.

Design your Search Bar

Write the code below to design and create the interface for your search bar.

const search_bar = {
   position: 'relative',
   background: 'transparent',
   width: '70%',
   left: '15%',
   top: '10%'
};

const form_style = {
   width: '100%',
   display: 'flex'
};

const search_input = {
   width: '80%',
   border: 'none',
   outline: 'none',
   padding: 15,
   borderTopLeftRadius: 10,
   borderBottomLeftRadius: 10,
   marginLeft: 1,
   fontFamily: '"PingFang SC", "Microsoft Yahei", Helvetica, Arial, sans-serif',
   fontSize: '18px',
   color: 'black'
}

 const search_btn_go = {
   borderTopRightRadius: 10,
   borderBottomRightRadius: 10,
   border: 'none',
   background: '#f7f7f7',
   width: '100%'
}

return <div style={search_bar}>
           <div style={form_style}>       
              <form>
                <input style={search_input} placeholder='Search' type="text" value="" />
              </form>

              <button style={search_btn_go}>
                <FontAwesomeIcon style={{width: '15px', height: '30px', marginBottom: '4px', marginTop: '5px', 
                color: 'rgb(0, 0, 0, 0.6)'}} icon={faSearch} />
              </button>
            </div>
      </div>

The code above shows how you can design a simple search input along with a search button. Create a parent div and add some style to it to determine its position on page. Next create a div for your search elements, and give it a desired styling to make the elements appear in a single line. Then add your input field inside the form tag and style it accordingly. Next, create your search button, and add your button style. To add the search icon, we have used the FontAwesomeIcon library and the ‘faSearch‘ icon. This makes a basic search bar with input field and search icon. Next, you can add onClick and hover events to your search bar.

Add Events to Search Elements

We now need to add events to control search input and hover states.

const [text, setText] = useState("");

const handleChange = (e) => {
   e.preventDefault();
   setText(e.target.value);
};

const handleSearchURL = (event) => {
   event.preventDefault();
   var search_url;
   if(text != ""){
      search_url = 'https://scratchcoding.dev/trk/t.php?q='+text
      window.open(search_url, "_blank");
   } else {
     console.log("Please Enter Search Keyword");
   }
}

const search_bar = {
   position: 'relative',
   background: 'transparent',
   width: '70%',
   left: '15%',
   top: '10%'
};

const form_style = {
   width: '100%',
   display: 'flex'
};

const search_input = {
   width: '80%',
   border: 'none',
   outline: 'none',
   padding: 15,
   borderTopLeftRadius: 10,
   borderBottomLeftRadius: 10,
   marginLeft: 1,
   fontFamily: '"PingFang SC", "Microsoft Yahei", Helvetica, Arial, sans-serif',
   fontSize: '18px',
   color: 'black'
}

 const search_btn_go = {
   borderTopRightRadius: 10,
   borderBottomRightRadius: 10,
   border: 'none',
   background: '#f7f7f7',
   width: '100%'
}

return <div style={search_bar}>
           <div style={form_style} onSubmit={handleSearchURL}>       
              <form>
                <input style={search_input} placeholder='Search' type="text" value={text} onChange={handleChange}/>
              </form>

              <button style={search_btn_go} onClick={handleSearchURL}>
                <FontAwesomeIcon style={{width: '15px', height: '30px', marginBottom: '4px', marginTop: '5px', 
                color: 'rgb(0, 0, 0, 0.6)'}} icon={faSearch} />
              </button>
            </div>
      </div>

Firstly we will define the required states, for the input text and hover state. This makes the text variable change whenever the input data is changed, and the text value is passed as search input value. Next, we handle our search input on submit or search button press. The handleSearchURL event reads the input text, creates a search URL using it, and then opens the relative search page. These are the main events involved for the Search Component functioning.

Add Additional States

To make your search bar attractive, and more user friendly, you can add hover events to your search button. Firstly add a hover state for it.

const [hover, setHover] = useState(false);

You can then use this hover state on onMouseEnter and onMouseLeave events on your search button as shown below.

<button style={search_btn_go} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} 
   onClick={handleSearchURL}>
    <FontAwesomeIcon style={{width: '15px', height: '30px', marginBottom: '4px', marginTop: '5px',
     color: hover ? 'rgb(255, 255, 255, 1)' : 'rgb(0, 0, 0, 0.6)',
    }} icon={faSearch} />
</button>

As shown in the code above, you can set the hover state as true and false based on the mouse events on your button. As per the hover state, you can change your search icons color and even its background color.

Complete Search Bar

The snippet below shows the complete code to design and handle events for your Search Component.

import React, {useState} from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSearch } from '@fortawesome/free-solid-svg-icons';

const SearchBar = () => {
  const [text, setText] = useState("");
  const [hover, setHover] = useState(false);

 const handleChange = (e) => {
   e.preventDefault();
   setText(e.target.value);
 };

 const handleSearchURL = (event) => {
   event.preventDefault();
   var search_url;
   if(text != ""){
      search_url = 'https://scratchcoding.dev/trk/t.php?q='+text
      window.open(search_url, "_blank");
   } else {
     console.log("Please Enter Search Keyword");
   }
 }

 const search_bar = {
   position: 'relative',
   background: 'transparent',
   width: '70%',
   left: '15%',
   top: '10%'
 };

 const form_style = {
   width: '100%',
   display: 'flex'
 };

 const search_input = {
   width: '80%',
   border: 'none',
   outline: 'none',
   padding: 15,
   borderTopLeftRadius: 10,
   borderBottomLeftRadius: 10,
   marginLeft: 1,
   fontFamily: '"PingFang SC", "Microsoft Yahei", Helvetica, Arial, sans-serif',
   fontSize: '18px',
   color: 'black'
 }

 const search_btn_go = {
   borderTopRightRadius: 10,
   borderBottomRightRadius: 10,
   border: 'none',
   background: hover ? 'rgb(0, 0, 0, 0.6)' : '#f7f7f7',
   width: '100%'
 }

 return <div style={search_bar}>
           <div style={form_style} onSubmit={handleSearchURL}>       
              <form>
                <input style={search_input} placeholder='Search' type="text" value={text} onChange={handleChange}/>
              </form>

              <button style={search_btn_go} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} 
                onClick={handleSearchURL}>
                <FontAwesomeIcon style={{width: '15px', height: '30px', marginBottom: '4px', marginTop: '5px',
                 color: hover ? 'rgb(255, 255, 255, 1)' : 'rgb(0, 0, 0, 0.6)',
                 }} icon={faSearch} />
              </button>
            </div>
      </div>
}

export default SearchBar;

You can find the required imports, styling, hover states, and div structure for your search bar.

The Search Bar component can be imported in your App.js or any other React file using the code below.

import SearchBar from './components/search_bar';

Then simply place your Search Bar in the return div of your component as shown below.

<SearchBar/>

The code above will create the following search bar for you.

search bar