Make CSS dependent on innerText of ais-Hits-item

instantsearchjs
rails

#1

I have setup Algolia instantsearch in a Rails application. I am indexing a single table with the attributes ‘thumbnail’, ‘name’, and ‘invitation_status’.

I would like the CSS of the orange button to be dependent on the value of ‘invitation_status.’ E.g. if the value is ‘Challenge’, I would like the button to be orange (.btn-primary), but if the value is ‘Pending…’ I would like the button to be grey (.btn-secondary).

Because I’m using the ‘hits’ widget I don’t have access to the DOM on page load, and I also just want to avoid workarounds such as using DOMContentLoaded, Promises, async, etc. How can I use parameters in the widgets to check for the innerText of each ais-Hits-item and set classes based on that?

Knowing the way to use Algolia’s indexed attribute values in the logic of the DOM, in general, would be very helpful.

Thank you!

44%20PM

search.addWidget(
  instantsearch.widgets.hits({
    container: '#hits',
    templates: {
      empty: 'Sorry no matching Peers',
      item: `
        <div class='d-flex hit align-items-center'>
          <img src="{{receiver_profile_thumbnail_url}}" align="left" alt="{{email}}" />

          <div class="hit-name">
            {{#helpers.highlight}}
            { "attribute": "name" }
            {{/helpers.highlight}}
          </div>

          <div class='ml-auto challenge-button'>
            <button id="challenge-button" type="submit" class='btn btn-primary authentication-buttons py-1'> 
              {{#helpers.highlight}}
              { "attribute": "invitation_status" }
              {{/helpers.highlight}}
            </button>
          </div>

        </div>
      `,
      cssClasses: {
        root: 'row',
        item: 'col-sm-12'
      }
    },
  })
);

#2

Hi Tyson,

Thanks for contacting Algolia!

To best help you, we would need to see the issue live for example with a live URL or if you replicate it in a codesandbox, and in each case with steps to replicate the issue (e.g., “You type in X, and then see empty boxes”). You can start with this codesandbox boilerplate if helpful:

Please let us know how it goes. We look forward to your reply!

Best regards,


#3

Thank you for your response. In my sandbox you can see that I have styled each { “attribute”: “name” } in the ‘hits’ widget with a RED background.

Now, instead of having long “name” values like “Amazon - Fire TV Stick with Alexa Voice Remote - Black”, let’s say my names are instead just one word like “Amazon”, “Google”, “HP”, and “Dell”.

Here is what I’m going for: If a “name” value == “Amazon”, it should have a PURPLE background, “Google” values should have a GREEN background, “HP” needs a BLUE background, and “Dell” should have a YELLOW background.

Where can I style an attribute based on it’s value? I hope that makes sense. I can try to setup a sandbox with my own index but I’m still a beginner. Thanks again!

https://p7804r8q8m.codesandbox.io/