'Name of this switch operator syntax
I am constantly finding this sort of switch statement in a codebase and not being able to find documentation about it anywhere. Does anyone know the name of this syntax?
import React from 'react'
enum Options {
FirstOption = 'first',
SecondOption = 'second'
}
export default function DisplayIcon({selectedOption: string}) {
const clickFirst = () => {
// do something
}
const clickSecond = () => {
// do something
}
return (
<Wrapper>
{
{
[Options.FirstOption]: (
<ClickableIcon onClick={ clickFirst }>
<Icon type={ IconType.Frist } />
</ClickableIcon>
),
[Options.SecondOption]: (
<ClickableIcon onClick={ clickSecond }>
<Icon type={ IconType.Second } />
</ClickableIcon>
),
}[selectedOption]
}
</Wrapper>
)
}
Solution 1:[1]
This isn't specific to JSX, and isn't really a particular piece of syntax, but a combination of multiple. Let's simplify it a bit:
let result = {
[Options.FirstOption]: 'hello',
[Options.SecondOption]: 'goodbye',
}[selectedOption];
This will select either 'hello' or 'goodbye'. It does so by first creating an object, and then looking up a property on it. We could add an intermediate variable like this:
let options = {
[Options.FirstOption]: 'hello',
[Options.SecondOption]: 'goodbye',
};
let result=options[selectedOption];
The [...]: syntax is just to allow the keys themselves to be defined based on some other variable, rather than a literal string. We could instead add properties one at a time like this:
let options = {};
options[Options.FirstOption] = 'hello';
options[Options.SecondOption] = 'goodbye';
let result=options[selectedOption];
The result, as you already worked out, is equivalent to this:
let result;
if ( selectedOption === Options.FirstOption ) {
result = 'hello';
}
elseif ( selectedOption === Options.SecondOption ) {
result = 'goodbye';
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | IMSoP |
