DEV Community

Charity Parks
Charity Parks

Posted on

Creating a search function in React

Things to think about when adding a 'Search bar' to your React app.

Proper planning will save you alot of time in the long run when it comes to building your react components.

So, you decide that you want a user to be able to search your app for certain words. First off, where do you want the search bar to appear in your app? You want to put it inside a component that has access to State. Whether itself holds State OR State can be passed down to it (from Parent to Child).

Create an input value for your search field in the State Object. Set that input value to an empty string inside the state where its located. For example:

state = {
items: [ ],
item: { }
}

You will want to then create a method for the onChange event for the input into the search bar. I would use an arrow function so you bind the value of this. Use setState to be able to update the state.

Pass down props for the input value and the handle the onChange function for the input field of the search bar as props to the the component holding the search bar.

And finally create the search method using filter and includes!

Top comments (0)