I have a svelte app where I map channelcodes to imported logos and render that logo in a div that is in a focused or unfocused state. Currently I have been mapping 1 image and changing the CSS of the logo(SVG) conditionally. But I find it kind of hacky and makes more sense to switch between a focused and unfocused versions of the logo image. The style of the element I can change, but i don't know how to switch images through my mapping (I want to avoid long if statements or switch cases as there could be many logos).
How would I switch between two images? Let me know if more information is required. (One idea I thought was an array of two images and I pass in an index 0 or 1 somehow)
TS FILE
import { Television_ChannelCode } from '@gql/schema';
import Logo1 from '@logos/Logo1.svelte';
import Logo2F from '@logos/Logo2F.svelte';
import Logo2U from '@logos/Logo2U.svelte'
const map = new Map<Television_ChannelCode, any>();
map.set(Television_ChannelCode.News, Logo1);
//I want to switch between 2, use array?//
map.set(Television_ChannelCode.Sports, [Logo2F, Logo2U]);
export const getLogoFromTelevisionChannelCode = (
televisionChannelCode: Television_ChannelCode,
): any => {
return map.get(televisionChannelCode);
};
SVELTE FILE <--- Can change style but how to swap images??
{#if hasFocus}
<div class={focusedStyle}>
<svelte:component this={getLogoFromTelevisionChannelCode(channelCode)}/>
</div>
{:else}
<div >
<svelte:component this={getLogoFromTelevisionChannelCode(channelCode)}/>
</div>
{/if}
CodePudding user response:
In your example the if block could be avoided by combining the class
<div class={hasFocus ? 'focusedStyle' : 'unfocusedStyle'}>
<svelte:component this={getLogoFromTelevisionChannelCode(channelCode)}/>
</div>
Your approach with the array could work like this
<div>
<svelte:component this={getLogoFromTelevisionChannelCode(channelCode)[hasFocus ? 0 : 1]}/>
</div>
(if every channel had the two version array) but I think the better approach would be to stick to the one component per Logo version, handle the styling intern and export a hasFocus
flag from components, so it could look like this
<svelte:component this={getLogoFromTelevisionChannelCode(channelCode)} {hasFocus}/>