0

In react js, if someone used list object mapping to a list as follow:

const removeUser = (email)=>{
        alert(email)
    }

    const usersList = users.map((user) =>
        <li key={user._id}>
            {user.Name}
            { isAdmin && <FontAwesomeIcon icon={faTrashAlt}  onClick={removeuser(user.Email)}/>}
        </li>
    );

in here, the function inside onClick event is automatically triggered when mounting the list elements component. it will prompt alerts with email addresses automatically.

2 Answers2

2

In react - onClick should get a function to execute, not execute a function like you did.

Wrap your function with arrow key function like this and it will work:

const removeUser = (email) => {
    alert(email)
}

const usersList = users.map((user) =>
    <li key={user._id}>
        {user.Name}
        {isAdmin && <FontAwesomeIcon icon={faTrashAlt}  onClick={() => removeuser(user.Email)}/>}
    </li>
);
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35
1

You are passing the invocation of the method, you should pass a definition of a method instead.

const usersList = users.map((user) => (
     <li key={user._id}>
        { user.Name }
       { isAdmin && <FontAwesomeIcon icon={faTrashAlt} onClick={() => removeuser(user.Email)} /> }
      </li>
 ));
Naren
  • 4,152
  • 3
  • 17
  • 28