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!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay