Skip to main content
@spa-tools/utilities

inlineSwitch()

The inlineSwitch<K, V>() function mimics a switch statement, but what makes it special is that it can be passed inline to other functions as an argument. This usage really shines in React function components where you can use it to conditionally render JSX elements.

  • The generic K type is used to define the key type of the switch statement.
  • The generic V type is used to define the value type of the switch statement.

Usage

import { useState } from 'react';
import { inlineSwitch } from '@spa-tools/utilities';

// simple example that demos how a single console.log
// call can control flow of multiple outputs
const respStatus = 404;
console.log(
inlineSwitch<number, string>(respStatus, {
200: 'Yay, call succeeded :-)',
404: 'Hmmm, item not found :-/',
500: 'Ouch, something went bang :-(',
})
);

// a more poignant example for inlineSwitch is a
// React function component
function InlineSwitchExample() {
const [activeTab, setActiveTab] = useState(2);

return (
<Tabs onTabChange={setActiveTab}>
{inlineSwitch<number, JSX.Element>(activeTab, {
1: <Tab value={1}>Tab1</Tab>,
2: <Tab value={2}>Tab2</Tab>,
3: <Tab value={3}>Tab3</Tab>,
})}
</Tabs>
);
}

Arguments

NameTypeDescription
keyKThe key value to match against the switch statement.
caseObjectRecord<K, V>An object that maps keys to values for the switch cases. Each key is a case to match against the runtime provided value.

Returns

The matched value of type V.