-1

i am new to REACT.js and your advise would be much appreciated

  • i have a list of categories i have placed a post under
  • i would like to display categories only if there are categories present
  • i am unsure why i am getting a syntax error - looked through it over and over

enter image description here

i tried the below:

<span className="categories">
  {
    if (post.categories) {
      Object.values(post.categories).slice(0, 1).map((category) => {
        return(
          <span>{category.name}</span>
        );
      })
    } else {
      return null;
    } 
  }
</span>

but i get the error: Failed to compile enter image description here

BELOW ARE MY FILES

app/scr/components/Blog/Index.js

import Layout from '../../components/Layout/Layout';
import { Link } from 'react-router-dom';
    
class Index extends Component {
  render() {
    return(
      <Layout>
        <ul>
          {this.props.posts.map((post) => {
            if (post) {
              return(
                <li key={post.ID} className="card">
                  <div>{post.title}</div>
                  <div>{post.date}</div>
                  <span className="categories">
                    {
                      if (post.categories) {
                        Object.values(post.categories).slice(0, 1).map((category) => {
                          return(
                            <span>{category.name}</span>
                          );
                        })
                      } else {
                        return null;
                      } 
                    }
                  </span>
                </li>
              );
            } else {
              return null;
            }
          })}
        </ul>
      </Layout>
    );
  }
}

export default Index;
  
ARTLoe
  • 1,743
  • 2
  • 21
  • 54
  • 1
    https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator you are not using the if statememnt correctly – Cornel Raiu Aug 18 '20 at 21:54
  • 2
    More broadly: you can only interpolate JavaScripts *expressions*, not statements, in JSX (although they can be function expressions, which can have a body containing statements...). Think about what JS that JSX would be transpiled to and it should become obvious why. – jonrsharpe Aug 18 '20 at 22:04

1 Answers1

1

You are not using the inline conditional correctly.

You should do it like this:

<span className="categories">
  {post.categories ?
    Object.values(post.categories).slice(0, 1).map((category) => {
      return(
        <span>{category.name}</span>
      );
    }) : null}
</span>

You can read more about conditionals in React here and more specifically about inline conditionals here

Cornel Raiu
  • 2,758
  • 3
  • 22
  • 31