s-leg3ndz
s-leg3ndz

Reputation: 3528

React inline conditional return Unexpected token, expected

I would like add inline conditional in my React Component, but i don't understand why, React return Unexpected token, expected on the line posts.length ? :

class PostList extends Component {

  getPosts() {
    const posts = Post.find().fetch();
    return posts;
  }

  render() {
    const posts = this.getPosts();
    return (
      {posts.length ?
        <ul>
          {posts.map((post) => (
            <PostItem key={post.title} post={post} />
          ))}
        </ul>
      }
    );
  }

}

Anyone have idea ? My conditional is wrong ?

Thank you community !

Upvotes: 2

Views: 3913

Answers (2)

Anurag Awasthi
Anurag Awasthi

Reputation: 6233

Return null when expression evaluates as false.Also Dont use the {}, use this ()

class PostList extends React.Component {
    
      getPosts() {
        //const posts = Post.find().fetch();
       const posts = ["post1","post2"]
        return posts;
      }
    
      render() {
        const posts = this.getPosts();
        return (
            posts.length ?
              <ul>
                {posts.map((post) => (
                  <PostItem key={post.title} post={post} />
                ))}
              </ul>:
              null
        )
      }
    
    }
    
    class PostItem extends React.Component{
    render(){
      return (<div>{this.props.post}</div>)
    }
}

ReactDOM.render(<PostList />, document.getElementById("app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Upvotes: 4

Chris
Chris

Reputation: 59511

Here's a slight syntactic variation to anuragasaurus answer.

If there is no "else" in your condition you don't need a ternary expression condition ? value1 : value2. You can instead use a Short-circuit evaluation:

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && (anything) is short-circuit evaluated to false.
  • true || (anything) is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect. Also note that the anything part of the above expression is any single logical expression (as indicated by the parentheses).


class PostList extends Component {

  getPosts() {
    const posts = Post.find().fetch();
    return posts;
  }

  render() {
    const posts = this.getPosts();
    return (
      posts.length &&
        <ul>
          {posts.map((post) => <PostItem key={post.title} post={post} />)}
        </ul>
    );
  }    
}

Upvotes: 1

Related Questions