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?

3
  • 1
    {…} wraps an expression, like 2 + 2 or x ? y : z. An if statement is a statement, not an expression. Commented Jun 15, 2019 at 22:05
  • ah..I didn't know this. Thanks Commented Jun 15, 2019 at 22:06
  • 2
    In any case it would have to be if (todos && todos.length). The parens are part of the if syntax. Commented Jun 15, 2019 at 22:07

2 Answers 2

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!");
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.