0

I am using ReactJS functional component to display a list of attachments and want to pass a parameter through an onClick on the attachment div but the parameter I am getting in the function handleAttachmentClick is undefined. I am displaying the attachments using {attachments} in the return function. Below are the related code:

const [attachmentclicked, setAttachmentClicked] = useState({})

const [visible, setVisible] = useState(false)

const [attachments, setAttachments] = useState([])

useEffect(() => {
  displayAttachments();
}, [])

const handleAttachmentClick = (attachmentclick) => {
  console.log(attachmentclick)
  setAttachmentClicked(attachmentclick)
  setVisible(true)
}

const displayAttachments = () => {
  if (props.data.attachment.length > 0) {
    for (i=0; i<props.data.attachment.length; i++) {
      console.log(props.data.attachment[i])
      tempattachments.push(<div onClick={() => 
      handleAttachmentClick(props.data.attachment[i])}><PaperClipOutlined /><span> 
      {props.data.attachment[i].filename}</span></div>)
      setAttachments(tempattachments)
    }
  }
}

return (
    <div>
        {attachments}
    </div>
)

An example of the return of the console.log(props.data.attachment[i]) in displayAttachments:

{size: 10210, data: "_9j_4AAQSkZJRgABAQAAAQABAAD_2wCEAAkGBxMTEhUTEhMWFh…CQPEQK1UXUqpJqc4loII6cCCCCAAggggAIIIIACCCCAD_2Q==", result: {…}, filename: "1x1_red_pixel.jpeg", type: "image/jpeg"}

However, the console.log(attachmentclick) in handleAttachmentClick returns undefined.

  • Put the `let` keyword before the `i = 0` in the `for` loop – Robin Zigmond Jul 04 '20 at 12:46
  • Can you share `attachments` state variable ? – akash Jul 04 '20 at 12:48
  • @RobinZigmond I have declared the i beforehand. Sorry I didnt include inside my example code. – Ang Yang Cheng Jul 04 '20 at 13:02
  • @akash the attachments state variable is set with the tempattachments inside displayAttachments. – Ang Yang Cheng Jul 04 '20 at 13:03
  • @AngYangCheng the problem isn't the lack of declaration, it's that you need to have each loop iteration have an `i` with its own scope. This is exactly what using `let` in the loop header does. Please try it, it is the easy solution to this problem. (Which is very common, or at least was before `let` became widespread in JS - see the duplicate I linked to.) – Robin Zigmond Jul 04 '20 at 13:05
  • @RobinZigmond thanks for the reply. it is working now. – Ang Yang Cheng Jul 04 '20 at 13:53

0 Answers0