Tuzi
Tuzi

Reputation: 160

If-else statement in .map loop in JSX

Instagram clone:

I want to check if I follow my follower then display <button>unfollow</button> or if not display <button>follow</button>

var IfollowAndHeFollowMe;

myfollowers.map(follower => {
     return(
       <div>
          <div>{follower.userName}</div>
          { IfollowAndHeFollowMe = 
            myfollowings.filter((following) => following.userName == follower.userName)
          }


          // this doesn't work

         { IfollowAndHeFollowMe.length > 0 ? return( <button>unfollow</button>): return(<button>follow</button>) }


         // and this also doesn't work

         { return IfollowAndHeFollowMe.length > 0 ? <button>unfollow</button> : <button>follow</button>}


       </div>
    )
})

//https://instagram-app-clone.netlify.app/ --- just for phone ---

Upvotes: 2

Views: 132

Answers (2)

Tuzi
Tuzi

Reputation: 160

// now dont have errors but its allways display button with follow text

{Data[2][0].followers.map(follower => {
                idFollowers++;

                return (

                    <div className="follower" id={idFollowers}  >
                        <img src={follower.profilna} className="profilnaFollower" alt="" />

                        <div className="userInfoFollower">
                            <h3>{follower.userName}</h3>
                            <p>{follower.name}</p>
                        </div>

                        {dbFollow = Object.entries(Data[2][0].following).filter(following => following.userName == follower.userName)}
                        {dbFollow.length > 0 ? (<button>unfoldasdaslow</button>) : (<button>fodsadsllow</button>)}
                    </div>
                )
            })}
        </div>

Upvotes: 0

Eugene
Eugene

Reputation: 613

JSX Code inside {} should be written as statements.

https://reactjs.org/docs/conditional-rendering.html

const followers = ['John', 'Hanna'];

function RenderMap() {
    return (
        <React.Fragment>
            {followers.map(follower => (
                <div>
                    <span>{follower}</span>
                    {followers.length > 0 ? (
                        <button>unfollow</button>
                    ) : (
                        <button>follow</button>
                    )}
                </div>
            ))}
        </React.Fragment>
    );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Upvotes: 4

Related Questions