Reactjs Creating Button with a onlick function that has a parameter

I have created a table that automaticly adds all the products from the database:

 <tbody>
                    {allproducts.map(allproducts =>
                   
                        <tr key={allproducts.id}>
                            <td>{allproducts.title}</td>
                            <td>{allproducts.price}</td>
                            <td>{allproducts.quantity}</td>
                            <td> <button className="DeleteButton" onClick=({this.deleteProduct({allproducts.id}) }) }) >delete</button></td>
                        </tr>
                    )}
                </tbody>

it is about this part:

<td> <button className="DeleteButton" onClick=({this.deleteProduct({allproducts.id}) }) >delete</button></td>

i want to pass the “id” into the function
i remmber in javascript it was as simple as

DeleteButton.setAttribute("onclick", `deleteProduct(${item.id})`);

how do i achive this with reactjs?

This:

onClick=({this.deleteProduct({allproducts.id}) })

First, I’m not sure about your various parentheses and curly braces - that’s not even valid JS.

Usually there are a few options here.


Everyone starts out trying this, but it won’t work:

onClick={ this.deleteProduct(allproducts.id) }

The problem is that you invoke the method immediately, even before the button is pressed. This only works if that function returns a function, probably not what you have in mind.


You can just pass a function:

onClick={ this.deleteProduct }

The onClick passes the event to the method - so if you can get the info you need off that, that’s great.


If you need other parameters, you need to wrap it in an anonymous function:

onClick={ e => this.deleteProduct(e, allproducts.id) }

With this, the click event will be the first parameter passed to the method, and your data after that.


If you don’t need the event at all, you can just do this:

onClick={ () => this.deleteProduct(allproducts.id) }

it may look a little odd at first, but hat is a pretty common pattern in React. It passes in the data you want and keeps it from running until you click that button.

2 Likes

wow the more i learn to more I appreciate the react Framework.
thank you very much.

just a little question aside from this. I was thinking about learning angular as well
after i understand Reactjs fully.
would you recommend that for job opportunities?

I would think that focussing on one and getting really good at that would be better for getting a job. If you master one, then I guess it couldn’t hurt, but since you will almost certainly be using one or the other, I think mastering one should be more of a priority.

Alright thank you very much :+1:

I have noticed that when i try to create a button outside of the return section on the bottom, a onClick function is not working am i correct?

this is my full code:

import React, { Component } from 'react';

export class Upload extends Component {
    constructor(props) {
        super(props);
        this.state = {
            Title: "empty",
            Price: 1,
            Description: "empty description",
            quantity: 2,
            loading: true,
            person: null,
            allproducts: []
        };
    }

    componentDidMount() {
        this.getData();
    }

    static productTable(allproducts) {
        return (
            <table id="ProductTable">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Price</th>
                        <th>Quantity</th>
                        <th>Edit</th>
                    </tr>
                </thead>
                <tbody>
                    {allproducts.map(allproducts =>
                   
                        <tr key={allproducts.id}>
                            <td>{allproducts.title}</td>
                            <td>{allproducts.price}</td>
                            <td>{allproducts.quantity}</td>
                            <td><button onClick={this.deleteProduct}>delete 1</button></td>
                            
                        </tr>
                    )}
                </tbody>
                </table>
                    );
                }

    deleteProduct = (id) => {
        fetch('api/Upload/' + id, {
        method: 'DELETE'
        })
        .then(() => this.getData())
        .catch(error => console.log("we cannot delete this:", error))

    }

    async getData() {
        const url = 'api/Upload';
        const response = await fetch(url);
        const data = await response.json();
        console.log(data);
        this.setState({
            allproducts: data,
            loading: false
        });
    }

    uploading = () => {
        let item =
        {
            title: this.state.Title,
            price: this.state.Price,
            description: this.state.Description,
            quantity: this.state.quantity
        };
        fetch('api/Upload', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(item)
        }).then(response => response.json())
            .catch(error => console.error("unable to achive this", error))
            .then(data => {
                console.log('succes', data);
              this.getData();
            });

    }

    TextHandler = (event) => {
        let name = event.target.name;
        let val = event.target.value;
        this.setState({ [name]: val });
    }

   

    render() {
        let content = this.state.loading
            ? <p><em> loading...</em></p>
            : Upload.productTable(this.state.allproducts);

        return (
         <div className="content">
           <div id="upload">
                <h1>Upload here</h1>
      
                <p>Title: { this.state.Title }</p>
                    <input
                        id="Title"
                        type="text"
                        name='Title'
                    onChange={this.TextHandler} />


                <p>Price: {this.state.Price}</p>
                <input
                    id="Price"
                        type="text"
                        name='Price'
                        onChange={this.TextHandler} />

                    <p>Description: {this.state.Description}</p>
                    <textarea
                        id="Price"
                        type="text"
                        name='Description'
                        onChange={this.TextHandler} />

                    <p>Quantity: {this.state.quantity}</p>
                    <input
                        id="quantity"
                        type="text"
                        name="quantity"
                        onChange={this.TextHandler} />

                <button id="uploadbutton" onClick={this.uploading}>Upload the product</button>
                    {content}
            </div>

            


           </div>


        );
    }


}

it is about the table part:

           <table id="ProductTable">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Price</th>
                        <th>Quantity</th>
                        <th>Edit</th>
                    </tr>
                </thead>
                <tbody>
                    {allproducts.map(allproducts =>
                   
                        <tr key={allproducts.id}>
                            <td>{allproducts.title}</td>
                            <td>{allproducts.price}</td>
                            <td>{allproducts.quantity}</td>
                            <td><button onClick={this.deleteProduct}>delete 1</button></td>
                            
                        </tr>
                    )}
                </tbody>
                </table>

Why is that a static method? What does this mean inside a static method? I’m asking because I really don’t know. How would it know to which instance you are referring?

its from the asp net core React template. but i think its better to put that list into the render secton at the bottom ?

I think it’s better to learn the fundamentals of React than to cut and paste code you don’t understand. This is not the first time we’ve had this discussion, if I remember correctly. You need to focus on fundamentals if you really want to learn this stuff.

For starters, I would try not making that method static.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.