D
D
Dmitry2019-03-29 00:16:43
React
Dmitry, 2019-03-29 00:16:43

How to correctly bind this plus additional parameters to a click handler in React?

Hello, there is a component

productSingle.js

import React, {Component} from 'react';
import {Link} from 'react-router-dom';
import ProductPrices from './ProductPrices';
import ReactHtmlParser from 'react-html-parser';
import history from '../../helpers/history';

class ProductSingle extends Component {

    constructor(props){
        super(props);

        this.postSelectedHandler = this.postSelectedHandler.bind(this, id);
    }

    postSelectedHandler(id, e){
        e.preventDefault();
        
        console.log( 'id', id );
        console.log( 'e', e );
    }

    render(){

        const {image, title, excerpt, descrtitle, descrtext, regular_price, sale_price, discount, currency, id, matchPath} = this.props;

        return (
            <div className="good__item">
                <div className="good__itemInner">
                    <div className="good__itemContent">
                        <div className="good__itemHeader">
                            <img className="good__itemImage" src={image} data-id={id} alt=""/>
                        </div>

                        <div className="good__itemTitle">{ReactHtmlParser(title)}</div>

                        <div className="good__itemExcerpt">{ReactHtmlParser(excerpt)}</div>

                        <div className="good__itemDescr">
                            <a
                                href={`${matchPath}/${id}`}
                                className="good__itemDescrTitle"
                                onClick={this.postSelectedHandler}
                            >
                                {ReactHtmlParser(descrtitle)}
                            </a>
                        </div>

                        <ProductPrices regular_price={regular_price} sale_price={sale_price} currency={currency} />
                    </div>
                </div>
            </div>
        );
    }
}

export default ProductSingle;

It has a link
<a
    href={`${matchPath}/${id}`}
    className="good__itemDescrTitle"
    onClick={this.postSelectedHandler}
>

Handler
postSelectedHandler(id, e){
        e.preventDefault();
        
        console.log( 'id', id );
        console.log( 'e', e );
    }

I bind this in the constructor following the guideline
, why is id undefined? How to properly bind an additional parameter through the constructor?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-03-29
@ddimonn8080

why is id undefined?

And you pass undefined there.
Corrected version:
constructor(props){
  super(props);

  this.postSelectedHandler = this.postSelectedHandler.bind(this, this.props.id);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question