DEV Community

Raj Bhinde
Raj Bhinde

Posted on

Search Functionality using Formik

Hi there! I have made this beginner friendly blog to create a simple search functionality where we would be getting the inputs from a form, and then by using a simple function we can sort the inputs received from the dummy data that we'll create.

While building this functionality, we're going to use useFormik() React hook as it makes the state handling of all the input elements easier especially when you have many input fields. You'll see the benefit of Formik further in the blog.

Enough talking, let's get coding!

Step 1- Create a dummy data

export const dummyObject = [
  {
    id: "1",
    firstName: "Raj",
    lastName: "Bhinde",
    userLocation: "Mumbai"
  },
  {
    id: "2",
    firstName: "Smrithi",
    lastName: "Mohandas",
    userLocation: "Bangalore"
  },
  {
    id: "3",
    firstName: "Dhaval",
    lastName: "Bhinde",
    userLocation: "New Jersey"
  },
  {
    id: "4",
    firstName: "Mohit",
    lastName: "Bhinde",
    userLocation: "Thane"
  },
  {
    id: "5",
    firstName: "Shubham",
    lastName: "Dawkhar",
    userLocation: "Pune"
  }
];

Enter fullscreen mode Exit fullscreen mode

Step 2- Create the input elements

<form>
   <label htmlFor="firstName">First Name</label>
   <input type="text" />
   <label htmlFor="lastName">Last Name</label>
   <input type="text" id="lastName" />
   <label htmlFor="location">Location</label>
   <input type="text" id="location"/>
</form>
Enter fullscreen mode Exit fullscreen mode

Step 3- Integrate useFormik() in our code

const formik = useFormik({
    initialValues: {
      firstName: "",
      lastName: "",
      userLocation: ""
    },
    onSubmit: (values) => {
      console.log(values);
    }
  });
Enter fullscreen mode Exit fullscreen mode

Now, the changes in the input elements would look something like this

<form onSubmit={formik.handleSubmit}
<input
      aria-label="input-firstName"
      id="firstName"
      type="text"
      onChange={formik.handleChange}
      value={formik.values.firstName}
/>
</form>
Enter fullscreen mode Exit fullscreen mode

You can continue using the same syntax of onChange & value for each & every input box irrespective of its type. This is where formik helps in getting rid of writing the spread operator & the syntax. It takes care of the state updates by itself.

Now, when we press the Submit button, we can see our input values in the console. That's happening because of the onSubmit functionality we passed in step 3 & console logging the values which got passed in the input.

Let's get rolling towards the next step!

Step 4- Get rid of the empty values.

Since we're creating a search functionality, we only want to filter using the values we provided in the input & get rid of the empty values which are returned by the formik. So let's create a function for that.

Before you look into the solution below, try to write a function for this by yourself. Basically you just have to delete the empty values of the keys in the JSON object.

const filterFunction = (values) => {
    const data = {...values};
     Object.keys(data).forEach((key) => {
      if (data[key] === "") {
        delete data[key];
      }
    });
}
Enter fullscreen mode Exit fullscreen mode

Now, at the place of console.log at the onSubmit let's call this function with values as the argument. You'll be able to see that, we're getting a JSON, only of the values which we entered in the input.

Step 5 - Let's create a function to filter the data

Before you look into the solution below, try to write a function for this by yourself. Here, we are trying return the data where the key & value of our object matches with the dummyObject we created.

    var finalObject = dummyObject.filter(function (item) {
      for (var key in data) {
        if (item[key] !== data[key]) return false;
      }
      return true;
    });
    setSearchResults(finalObject);
Enter fullscreen mode Exit fullscreen mode

Note that I've created a useState here to store the results of final Object & access it outside of the function to display the data.

Step 6 - Let's display the data. Write the below code outside of your form tag.

{searchResults.length !== 0 &&
        searchResults.map((value, key) => {
          return (
            <div key={key}>
              {value.firstName} {value.lastName} {value.userLocation}
            </div>
          );
        })}
Enter fullscreen mode Exit fullscreen mode

Voila! We now have a form with a search functionality.

If you've reached this far, thanks for reading my first blog. Any kinds of queries & feedback are most welcome.

Embedding a CodeSandBox Link here incase anyone needs it -

Top comments (2)

Collapse
 
irajbhinde profile image
Raj Bhinde

Hey! Sorry for the late response. That's a nice way to get your form data as well. But the data that we got is in array format, I tried playing around with your CSB but wasn't able to figure out a way to delete the empty key fields from the array, it returned an undefined for the fields with "" values. This was my code -

const func =  data.map((item) => {
  if (item[1] === "") {
    delete data[item];
  } else{
    return item;
  }
});
console.log(func);
Enter fullscreen mode Exit fullscreen mode

Not sure if this was the right approach though.

 
irajbhinde profile image
Raj Bhinde

This is awesome! Learned a new approach today, thanks! ;)