Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you send arguments from map() to another function in React

I’m having difficulty in sending an argument using an onClick function inside an iterating map() function. Here’s what I have tried so far:

Initially, with this, there’s an error on {Product._id}, stating "Parsing error: Unexpected token, expected ",""

import Axios from 'axios';
import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router';

export default function ProductCatalog() {

    let navigate = useNavigate();

     function deleteProduct(id){
        window.location='/delete/'+id
     }

    const [products, setProducts] = useState([{}])

    const useProducts = products.map((Product)=>{
                    return (

                            <p>{Product.Description}</p>

                            <span className="icon-del" onClick={() =>this.deleteProduct{Product.id})}>
                                                /*some image here*/
                            </span>     
                      );
                })

    return(
        <React.Fragment>
                {useProducts}
        </React.Fragment>
        )
}

Next I tried to create a variable called newID outside the arrow function, and in the onClick function, I used a setter to set the value I needed when that product is clicked on, but I got another error stating: "ProductCatalog.js:48 Uncaught TypeError: Cannot read properties of undefined (reading ‘setID’)"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m unsure what I’m doing wrong here – fairly new to React.

Edited to remove syntax error on onClick. Remaining error: ProductCatalog.js:46 Uncaught TypeError: Cannot read properties of undefined (reading ‘deleteProduct’)
at onClick (ProductCatalog.js:46:1)

>Solution :

You have syntax error.

Change this line

<span className="icon-del" onClick={() =>this.deleteProduct{Product.id}}>

to this.

<span className="icon-del" onClick={() =>deleteProduct(Product.id)}>

You don’t need this keyword in functional components.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading