I am trying to return an element with an inline switch. But I am getting only a empty <span> </span>
. What am I doing wrong?
getRowTdForHeader: (header: string, entry: response) => {
return (<span>
{() => {
switch (header) {
case "Name": return entry.name;
case "Type": return entry.type;
default: return entry.name;
}
} }
</span>);
}
Result is a empty span
and if I put a breakpoint at the return, it never goes into the switch statement at all. I'd like to keep it as a in-liner if possible. The switch works fine if I don't inline it btw.
I am trying to return an element with an inline switch. But I am getting only a empty <span> </span>
. What am I doing wrong?
getRowTdForHeader: (header: string, entry: response) => {
return (<span>
{() => {
switch (header) {
case "Name": return entry.name;
case "Type": return entry.type;
default: return entry.name;
}
} }
</span>);
}
Result is a empty span
and if I put a breakpoint at the return, it never goes into the switch statement at all. I'd like to keep it as a in-liner if possible. The switch works fine if I don't inline it btw.
-
First, I don't see purpose for
()=>
Second, even switch is not required. You can doentry[(header || 'name')]
– Rajesh Commented Jan 24, 2017 at 10:04 -
@Rajesh How does this work
entry[(header || 'name')]
? – Murat Karagöz Commented Jan 24, 2017 at 10:11 -
1
entry
is an object and since you are returning property that is same word but different case,header.toLowercase()
will give you property name. So if header isName
,entry[header.toLowerCase()]
will returnentry['name']
.|| 'name'
is the default value. If header is not defined, returnname
. Also my apologies, I forgot.toLowerCase()
– Rajesh Commented Jan 24, 2017 at 10:15 - @Rajesh Alright thanks. But the header names do not necessarily reflect the property name. – Murat Karagöz Commented Jan 24, 2017 at 10:17
-
But will case always have return value only? If yes, I'd suggest to create a map and then just return
entry[map[header]]
– Rajesh Commented Jan 24, 2017 at 10:19
3 Answers
Reset to default 5You have to wrap the arrow function in parentheses and execute it immediately with a following pair of parentheses.
{(() => {
switch (header) {
case "Name": return entry.name;
case "Type": return entry.type;
default: return entry.name;
}
})()}
you defined a function but not call it
() => {
switch (header) {
case "Name": return entry.name;
case "Type": return entry.type;
default: return entry.name;
}
}
I suggest that you put the result into a variable and then use it:
getRowTdForHeader: (header: string, entry: response) => {
let str: string;
switch (header) {
case "Name": str = entry.name;
case "Type": str = entry.type;
default: str = entry.name;
}
return <span> { str } </span>;
}