简体   繁体   中英

React ternary operator error

I'm trying to only return firebase data that was only created by the user to their homepage using a ternary operator but I keep getting the error: Syntax error: Unexpected token, expected

Can anyone see where the code is going wrong? If I wrap the ternary around the remove button it'll work, only allowing the user to remove items created by them. I want to only display stuff created by them. The react code is below:

  <ul>
  {this.state.items.map((item) => {
    return (
      {item.user === this.state.user.displayName || item.user === this.state.user.email
      ? <li key={item.id}>
          <h3>{item.topic}</h3>
          <p>author: {item.user}
            <button onClick={() => this.removeItem(item.id)}>Remove Item</button>
          </p>
        </li>
      : null}
    )
  })}
  </ul>

Embedding Expressions in JSX:

You can embed any JavaScript expression in JSX by wrapping it in curly braces.


{} required when we want to put some js expression inside JSX, In your case it is not required. If you use {} it means you are trying to return an object.

Write it like this:

return (
    item.user === this.state.user.displayName || item.user === this.state.user.email?
        <li key={item.id}>
            <h3>{item.topic}</h3>
            <p>
                author: {item.user}
                <button onClick={() => this.removeItem(item.id)}>Remove Item</button>
            </p>
        </li>
    : null
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM