Home > Software engineering >  How to use if else condition in Reactjs
How to use if else condition in Reactjs

Time:01-18

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
           }
 ))}

CodePudding user response:

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

CodePudding user response:

You have to use a ternary condition :

{ condition ? a : b }

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

CodePudding user response:

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</> </>
           }
 })}
  • Related