SolidJSS
SolidJS3y ago
Ryan

How to handler this standard ReactJS pattern?

In React, I would normally do something like this:

<For each={autoCompleteStore.options}>
  {(option, optionIndex) => {
    const isHighlighted = optionIndex() === autoCompleteStore.focusedOptionIndex;

    return (
      <div
        data-id={`item${isHighlighted ? ' highlighted-item' : ''}`}
        class={classnames(styles.renderedItem, { [styles.highlightedItem]: isHighlighted })}
        onMouseEnter={() => onMouseEnterOption(optionIndex())}
        onMouseDown={() => selectValue(option)}
        role="button"
        tabIndex={-1}
      >
        {option.display}
      </div>
    );
  }}
</For>


Now with SolidJS since the function itself only runs once, this does not work and I am trying to figure out what the SolidJS / reactive pattern would be. Since I don't want to duplicate the code to check it is it highlighted for cleanliness, would the best practice for something like this be:

const isFocusedOption = (optionIndex: number) => {
  return autoCompleteStore.focusedOptionIndex === optionIndex;
};

// ...

<For each={autoCompleteStore.options}>
  {(option, optionIndex) => {
    return (
      <div
        data-id={`item${isFocusedOption(optionIndex()) ? ' highlighted-item' : ''}`}
        class={classnames(styles.renderedItem, { [styles.highlightedItem]: isFocusedOption(optionIndex()) })}
        onmouseenter={() => onMouseEnterOption(optionIndex())}
        onmousedown={() => selectValue(option)}
        role="button"
        tabindex={-1}
      >
        {option.display}
      </div>
    );
  }}
</For>
Was this page helpful?