Create an Expanding Search Box

In this blog post we will be creating a growing search box in React as seen in the image.

Expanding Search Box

As you can see initially it’s just a magnifying glass and when you hover your mouse over it, it expands. When you click inside and give it focus it will stay in expanded state. If you are observant you might have noticed the arrow at the end of the search box. You can easily setup a listener on the arrow that when clicked will dispatch an event and search can be performed.

I usually keep my styles in a separate file called styles but that is just a personal preference. We start off by creating a Container component which is nothing but a div. This hosts our search input. It’s important that we give it a position of relative otherwise the input which is a direct child of this div will not be positioned properly. You can read more about relative positioning and it’s effect on children here.

The search input is simply an input element with a couple of lines of CSS for styling. Since I am using Styled Components I can easily pass in props and utilize those props to change CSS which I think is pretty cool. This is how I am controlling the display from block to none, for example. The icons are pretty self explanatory and are SVGs housed in their own files.

Within the search component I tap into mouse enter and mouse leave events so that we can expand or shrink the search box as needed. The focus event is used to keep the search box in expanded state when user clicks within it.

Contact Us for more tutorials or feedback.