zookastos
zookastos

Reputation: 935

React - passing component prop in click handlers passed as props

I am new to React. I have a react component Child like this -

//this.props has obj = {'id': 123, 'name': 'abc'}
class Child extends React.Component{

    constructor(props){
        super(props);
    }
    render(){
        return(
            <div onClick={this.props.remove}></div>
        );
    }
}

This component is being used from some Parent component which has a list of such Child component, each having their own this.props.obj. this.props.remove is another handler passed to Child from Parent.

Now, on click of div redered from Child component, I want to pass this.props.obj.id in remove function. How can I do that.

Thanks

Upvotes: 2

Views: 450

Answers (2)

Csaba Farkas
Csaba Farkas

Reputation: 882

You can use arrow functions to achieve this.

class Child extends React.Component{

    constructor(props){
        super(props);
    }
    render(){
        return(
            <div onClick={() => this.props.remove(this.props.obj.id)}></div>
        );
    }
}

Upvotes: 0

ArchNoob
ArchNoob

Reputation: 4126

Welcome to React!

You can learn about event handlers here

I would write it up like this;

class Child extends React.Component{

    constructor(props){
        super(props);
    }

    handleClick({id}) {
       this.props.remove(id)
    }

    render(){
        const obj = this.props
        return(
            <div onClick={() => this.handleClick(obj)}></div>
        );
    }
}

Upvotes: 2

Related Questions