2

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.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
  • First, I don't see purpose for `()=>` Second, even switch is not required. You can do `entry[(header || 'name')]` – Rajesh Jan 24 '17 at 10:04
  • @Rajesh How does this work `entry[(header || 'name')]`? – Murat Karagöz Jan 24 '17 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 is `Name`, `entry[header.toLowerCase()]` will return `entry['name']`. `|| 'name'` is the default value. If header is not defined, return `name`. Also my apologies, I forgot `.toLowerCase()` – Rajesh Jan 24 '17 at 10:15
  • @Rajesh Alright thanks. But the header names do not necessarily reflect the property name. – Murat Karagöz Jan 24 '17 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 Jan 24 '17 at 10:19

3 Answers3

5

You 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;
                    }
})()}
Ardor
  • 154
  • 11
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
1

you defined a function but not call it

() => {
    switch (header) {
        case "Name":  return entry.name;
        case "Type": return entry.type;
        default: return entry.name;
    }
}
Jiang YD
  • 3,205
  • 1
  • 14
  • 20
1

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>;
}
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299