S
SolidJS2y 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>
<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>
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>
2 Replies
thetarnav
thetarnav2y ago
const isHighlighted = () => optionIndex() === autoCompleteStore.focusedOptionIndex
const isHighlighted = () => optionIndex() === autoCompleteStore.focusedOptionIndex
Ryan
RyanOP2y ago
Ah, never thought about inlining the function in the For but that does makes sense
Want results from more Discord servers?
Add your server