1

I am trying to access a method in a nested chilld component using refs. This is to delete data in the nested delete component. My code is as follows (simplified code):

Parent Class:

class Parent extends Component {
  constructor(props) {
    this.childref = React.createRef()
    props.refs(this)
  }
  render() {
    const elements = return [
     <div onclick={this.callsupprimer(0)} />,
     <div onclick={this.callsupprimer(1)} />
    ]
    return (
      <Fragment>
        <Child refs={ref => this.childref = ref>
        </Child>
       loadToolData()
     </Fragment>
     )
  }
  callsupprimer = index => this.childRef.GrandChildRef.supprimer(index)
}
 export withStyles(styles)(Parent)

Child Class:

class Child extends Component {
  constructor(props) {
    this.grandchildref = React.createRef()
    props.refs(this)
  }

  render() {
    return (
      <GrandChild refs={ref => this.grandchildref = ref>
      </GrandChild>
    )
  }
}
 export withStyles(styles)(Child)

GrandChild Class:

class GrandChild extends Component {

  supprimer = (index) => {
        console.log(index)
        this.forceUpdate()
  }
  render() {
    return (
      //blah blah blah
    )
  }
}
export withStyles(styles)(GrandChild)

However, I cannot get the supprimer method to invoke changes in the this context of GrandChild. The method gets called but, in a strange way.

it gets called once when the component is loaded and prints the index, but it does not work onlick!!! I don't even call this method in the grandChild class. Please help.

UPDATE: The code is exactly as written except for the method names now.

toing_toing
  • 2,334
  • 1
  • 37
  • 79

1 Answers1

0

The problem was that I was invoking the callsupprimer when rendering, when it should have been done only onClick, so the method was called once on rendering and it didn't work after. Once I changed the onClick in the parent class to an arrow function callback:

<div onclick={() => this.callsupprimer(1)} />

it worked as expected.

NB: when using withstyles, you need to use refs, and not ref, and then bind the this in the child component as in the question. I didn't need to use current. @Hai Alaluf 's comments in the question pointed me in the right way!

toing_toing
  • 2,334
  • 1
  • 37
  • 79