Home > Software engineering >  How do you send arguments from map() to another function in React
How do you send arguments from map() to another function in React

Time:10-24

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')"

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)

CodePudding user response:

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.

  • Related