Search code examples
javascriptreactjsonclickviteonchange

Onclick function not working in element which is inside map function


import React from 'react'
import user from './api/Userdata'
const Chats = () => {
  const seeMsg = (id) => {
    console.log(id)
  }
  return (
    <div className="main">
        { user.map((currUser) =>{
        const [name, id, time, image] = user;
        return(
        <div className="user w-full h-14 my-1 flex justify-between content-center" key={currUser.id}>
            <img className='shadow rounded-full max-w-full h-11 w-11 align-middle border-none' src={currUser.image} onClick={seeMsg(currUser.id)} alt=""/>
            <div className="name pr-16 pl-1 justify-center text-center flex items-center text-gray-900 font-medium mb-1">{currUser.name}</div>
            <div className="time font-thin text-xs text-center flex items-center pr-2">{ currUser.time }</div>
        </div>
          )})}
      </div>
  )
}

export default Chats

I'm trying to create a whatsapp clone. These are basic details that successfully printing. But I want when someone click on particular profile, its id will be printed in console using seeMsg(). So I use onclick but It shows error.


Solution

  • The issue you're facing is due to how you're using 'onClick' handler in your code. The 'onClick' handler expects a reference to a function, but in your current code, you're directly invoking the function when rendering the component. It should look like this:

    onClick={() => seeMsg(currUser.id)}