1

I'm going through some coding examples, and came across this one example of a component declaration in React:

export const TodoList = ({ todos }) => (
    <ul>
        {
            todos && todos.length
            ? todos.map((todo, index) => {
                return <Todo key={`todo-${todo.id}`} todo={todo} />
            })
            : "No todos, yay!"
        }
    </ul>
);

I wanted to try and turn this ternary operator into an if/else statement, like this:

export const TodoList = ({ todos }) => (
    <ul>    
        {
            if (todos) && (todos.length) {
                todos.map((todo, index) => {
                    return <Todo key={`todo-${todo.id}`} todo={todo} />
                })
            } else {
                "No todos, yay!"
            }
        }
    </ul>
);

But, I get the error at the line where the if statement begins:

Parsing error: Unexpected token

why is it that the ternary operator works here but an if statement doesn't?

rpivovar
  • 3,150
  • 13
  • 41
  • 79

2 Answers2

4

What comes between the {}s must be an expression. The conditional (ternary) operator evaluates to an expression; if, on the other hand, is a statement which cannot be evaluated as an expression. For similar reasons, this is invalid:

const foo = if (true) {
  'bar'
}

See If-Else in JSX:

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. Take this basic example:

// This JSX:
ReactDOM.render(<div id="msg">Hello World!</div>, mountNode);

// Is transformed to this JS:
ReactDOM.render(React.createElement("div", {id:"msg"}, "Hello World!"), mountNode);

This means that if statements don't fit in. Take this example:

// This JSX:
<div id={if (condition) { 'msg' }}>Hello World!</div>

// Is transformed to this JS:
React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

The if statement is flow control, whereas the ternary operator is a simple operator. The if statement expects code, the ternary operator expects values.

blenderfreaky
  • 738
  • 7
  • 26