Conditionally display refinement lists (React + Instantsearch)

I have a React app using Algolia to list items which can be filtered via refinement lists. I’m trying to work out how I can hide a refinement list until a different refinement list has a certain value selected.

Here is my component:

import React from 'react'
import { RefinementList } from 'react-instantsearch-dom'

const SidebarLocations = () => {
  return (
    <>
      <RefinementList attribute="states.name" operator="and" />
      <RefinementList attribute="preferences.name" />
      <RefinementList attribute="locations.name" limit={50} />
    </>
  )
}

export default SidebarLocations

An example of the desired behavior I’m looking to accomplish is, if the states.name refinement list has value X selected, then show the preferences.name refinement list.

Any help on this would be GREATLY appreciated.

have you tried passing down a state with the attribute as prop and render it like-

   <>
    <RefinementList attribute={attribute.name} operator={attribute.operator} />
   </>

I’m not sure I am following what you’re laying down here.

Hi @tgooden,

I would suggest using the transformItem prop in combination with a state.
In the function you pass you could check whether the value has been selected or not, and then update the state accordingly.

Following your example:

import React, { useCallback, useState } from 'react'
import { RefinementList } from 'react-instantsearch-dom'

const SidebarLocations = () => {
  const [showPreferences, setShowPreferences] = useState(false)

  const transformStatesItems = useCallback(items => {
    const targetItem = items.find(item => item.label === 'X')

    setShowPreferences(!!targetItem?.isRefined) 
    // `!!` turns an eventual undefined value into false

    return items
  }, [])

  return (
    <>
      <RefinementList attribute="states.name" operator="and" transformItems={transformStatesItems} />
      {showPreferences && <RefinementList attribute="preferences.name" />}
      <RefinementList attribute="locations.name" limit={50} />
    </>
  )
}

export default SidebarLocations

Let me know what’s your opinion about this approach :slight_smile:

Best,
Gabriele