Show recent searches on top - React, Javascript

Show recent searches on top – React, Javascript

In this tutorial, you will learn how you can show recent searches on top using React (Javascript). You might have seen in many apps that your most frequent searches appear on top.

So the first thing you need to do, is to create 2 state variables.

const [history, setHistory] = React.useState([]);
const [search, setSearch] = React.useState("");
  • history: This will keep track of all the search history.
  • search: This will be the current search on input field.

Then we need to create an input field and a button which when clicked, will add the searched item to the history.

<input type="text" placeholder="Type here..."
    value={ search }
    onChange={ onChangeSearch } />

<button type="button" onClick={ doSearch }>Search</button>

We need to create those 2 functions.

const onChangeSearch = function (event) {
    setSearch(event.target.value);
};

const doSearch = function () {
    let flag = false;
    let index = -1;
    for (let a = 0; a < history.length; a++) {
        if (history[a] == search) {
            flag = true;
            index = a;
            break;
        }
    }

    const temp = [ ...history ];

    if (!flag) {
        temp.push(search);
    }

    setHistory(temp);
};

First function will be called whenever you type something in input field. It will simply set the input field value to the state variable.

Second function will be called when you press the “Search” button. It will check if the searched item is not already in the list. If not, then it will append it in history array. If the term is already in history, then we can getting the index where it is found.

At this point, if you run the script, you will be able to search items and they will be displayed to you in the browser. But if you search the same item again, it will stay in the same position. We need to move it up by 1 step. So everytime you search, it gets closer to the top.

For that, you need to add an else block to your if condition.

if (!flag) {
    temp.push(search);
} else if (index > 0) {
    let h = temp[index];
    temp[index] = temp[index - 1];
    temp[index - 1] = h;
}

Here, we are simply swapping the current value with the previous one. if (index > 0) this condition makes sure that when an item reaches the top of the list, it should not be removed. If you do not put this condition, then once your item reaches the top and you search it again, it will be removed.

So that’s how you can show recent searches on top using React (Javascript). If you need any help in this, feel free to contact me.

Learn how to do case-sensitive search in MySQL.