Instantsearch.js Submit hide on search?

923 views Asked by At

Problem:

By default in instantsearch.js, the reset button in the search field is hidden until you start typing. However the submit button doesn't hide, causing them to overlap, this seems default behavior(?)

Here is a demo that demonstrates the issue: https://codesandbox.io/s/quizzical-leakey-7shzr

Expected Outcome:

I want the search submit button to replace (toggle) with the reset button on typing.

Things I've tried:

I have looked through the documentation and can't find any solution to this. There is a showReset and showSubmit parameters as seen here: https://www.algolia.com/doc/api-reference/widgets/search-box/js/ but these just disable them completely.

Changing the template for them in the widget, only stylizes them, rather than adjust their function.

I do have a heavy handed solution I've written in jquery below but my question is: Is there a way to configure this behavior in instantsearch.js?

$( ".ais-SearchBox-input" ).on("keyup", function() {
    if($('.ais-SearchBox-input').val().length > 0){
        $('.ais-SearchBox-submit').addClass('none');
    }else{
        $('.ais-SearchBox-submit').removeClass('none');     
    }
});
$(document).on('click', '.ais-SearchBox-reset', function() {
    $('.ais-SearchBox-submit').removeClass('none');     
});
1

There are 1 answers

0
Sarah Dayan On

The submit button is initially designed to be on the left hand side of the searchbox, and the reset one on the right hand side, as you can see in the InstantSearch.js SearchBox Storybook. In your demo, there's custom CSS that aligns them both on the right, which is why they're overlapping. But they're two orthogonal concepts, so they weren't designed to replace one another out of the box.

Your solution is fine, although I understand that having imperative logic like this on top of InstantSearch.js might feel icky. Another approach is to directly hook into the rendering logic of the widget by using the connectSearchBox connector. You'll be able to fully control what is rendered, and you'll have access to query which you'll be able to leverage to decide whether to show one button or the other.

My advice is to start from the full example and adapt it for your use case.