0

I have two components:
Parent.js

export default class Parent extends React.Component {
  handleTagHierClick(e) {
    var excel = this.refs.workbook;
    excel.click();
  }

  render() {
    return (
      <button onClick={(e) => this.handleTagHierClick(e)} className="btn btn-default btn-block">Download Tag Hier</button>
      <Child/>
    )
  }
}

And Child.js

import React from 'react';

export default class Child extends React.Component {
  render() {
    return (
      <div ref='workbook'></div>
    )
  }
}

How can I trigger a click on the div element from the Child component when I click on the button element from the Parent component? I tried with ref but that won't work since the elements are on different components...

Valip
  • 4,440
  • 19
  • 79
  • 150

2 Answers2

1

If I understood you right, you do it like

class Parent extends React.Component {

 handleTagHierClick(e) {
     this.child.someMethod();
 }

  render() {
    return (<div>
      <Child ref={(obj) => { this.child = obj; }}/>
      <button
         onClick={(e) => this.handleTagHierClick(e)}/>
      </div>
    );
  }
}

Inside child

import React from 'react';

export default class Child extends React.Component {
  someMethod(){
      // Here you can trigger click on the div
      this.div.click();
  }
  render() {
    return (
      <div  ref={(obj) => { this.div = obj; }}></div>
    )
  }
}
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
0

Did you try to add a ref to the button?

<button ref='myButton'...

Then replace the variable excel by:

var excel = this.refs.myButton.refs.workbook;
B. Bastien
  • 66
  • 3