2

I am working on Reactjs and using nextjs,Right now i am getting "cat_name"(category) inside map function(loop), i just want to add condition "if cat_name!="" || cat_name=="pinned" before fetching data How can i do this,Here is my current code

{students.data?.length > 0 &&
 students.data.map((blog) => (
// 
      {blog.cat_name}   // containing category,want to add condition here
       if(blog.cat_name)
           {
                //further code
           }
        else
          {
              // further code
           }
 ))}

3 Answers 3

2

You can use an inline conditional (ternary operator) to render one or the other. Note that you can only return one JSX element, that's why you would have to wrap them in a fragment or div

<>
  {students.data?.length > 0 &&
    students.data.map((blog) => (
      <>
        {blog.cat_name}
        {blog.cat_name ? <>Either</> : <>Or</>}
      </>
    ))}
</>;

References: https://reactjs.org/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

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

Comments

1

Your code is just about right. If you want to go with your syntax, arrow function with no return statement, you could use a ternary approach:

{students.data?.length > 0 &&
 students.data.map((blog) => (
    <> //fragment needed to wrap more than one node
      {blog.cat_name ? <>Something</> : <>Something else</>}
    </>
 ))}

Or you could go with the return statement, in which you would be able to do a "default" if-else statement.

{students.data?.length > 0 &&
 students.data.map((blog) => {
       if(blog.cat_name)
           {
                return <>{blog.cat_name} <>anything else you want here</> </>
           }
        else
          {
              return <>{blog.cat_name} <>anything else you want here</> </>
           }
 })}

Comments

1

You have to use a ternary condition :

{ condition ? a : b }

https://en.wikipedia.org/wiki/Ternary_conditional_operator

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.