Search code examples
javascriptreactjsreact-dropdown-tree-select

React TreeSelect inject custom filtering logic


I have been trying to alter logic in TreeSelect React component.

So, what I am trying to do is to search by value, but with trimmed spaces, for example if we have entries:

dog cat fish

when entering dog it should return me dog entry, simply - ignore spaces at the beginning, while still keeping them in UI.

I tried

const [filterValue, setFilterValue] = useState('')
...
<TreeSelect
    ...otherProps,
    filter
    filterValue={filterValue}
    onFilterValueChange={(e) => setFilterValue(e?.value?.trimStart())}
/>

but unfortunately this affects how component work and while typing spaces at the beginning, it also trims it in displayed value, giving wrong user experience.

QUESTION

Is there simple way I can somehow override this filtering?

Maybe somehow by changing equality comparison?


Solution

  • I finally found a way to work around it. Simply make the TreeSelect controlled component and supply your own input in panelHeaderTemplate property of TreeSelect.

    This way you can inject bit of extra logic in filtering:

    import { useCallback, useState, ChangeEvent } from 'react'
    ...
    const [filterValueProxyState, setFilterValueProxyState] = useState('')
    const handleFilterValueChange = useCallback(
      (event: ChangeEvent<HTMLTextAreaElement>) => {
        // here we trim filter proxy value, to filter by trimmed string in TreeSelect list
        setFilterValueProxyState(event.target.value.trimStart())
      },
      [props.onProxyFilterValueChange]
    )
    
    <TreeSelect
      panelHeaderTemplate={<textarea value={filterValue} onChange={handleFilterValueChange}/>}
      filterValue={filterValueProxyState}
      {...restProps}/>
    

    This is merely pseudo code, as most probably textarea is not best choice here, but I just wanted to describe how it could be achieved.