Gergő Horváth
Gergő Horváth

Reputation: 3705

How to access child component's child from parent component in react?

After hours of brainstorm, i decided to ask the question from you. The situation is that i use react-rnd, which is a draggable and resizable extension for react, which is a component with a few child components. I have this code right now:

    //this component has the property: id
    
    deleteEvent(){
        console.log(this.props.id) //returns undefined
    }
    render(){
        console.log(this.props.id) //returns correct value
        return(
            <Rnd>
                <div onClick={this.deleteEvent}></div>
            </Rnd>
        )
    }

As i see the DOM tree, in react devtools, the div is 5 levels down from this component. This is a big problem for me. I don't want to edit the Rnd's components. If i create a component for the button (the div), it doesn't help, because i still need to pass the id to the button. I considered about connecting the button component to redux, but it still doesn't know which id it has. So someone help me please to pass the right id to the div

Upvotes: 1

Views: 153

Answers (2)

Piyush Zalani
Piyush Zalani

Reputation: 3934

You have to either bind function in your constructor or you can use arrow function instead.

`

deleteEvent = () => {
        console.log(this.props.id) //returns undefined
    }
    render(){
        console.log(this.props.id) //returns correct value
        return(
            <Rnd>
                <div onClick={this.deleteEvent}></div>
            </Rnd>
        )
    }

`

Upvotes: 1

Ceddy Muhoza
Ceddy Muhoza

Reputation: 636

The deleteEvent() method must be declared in your component's constructor otherwise the deleteEvent method will not have access to this

constructor(props){
 super(props)
 this.deleteEvent = this.deleteEvent.bind(this)
}

deleteEvent(){
   console.log(this.props.id) //returns id
}

Upvotes: 2

Related Questions