-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;
  
2
  • 1
    reactjs.org/docs/… you are not using the if statememnt correctly Commented Aug 18, 2020 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. Commented Aug 18, 2020 at 22:04

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

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.