0

I do not understand what I am doing wrong. I am using react 16:

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

I am importing my script:

<script type="text/babel" src="/SiteAssets/my_script.js"></script>

and my_script.js is this

const FileReaderElement = React.createElement;

class FileReader extends React.Component {
  constructor() {
    super();
    this.my_csv_link = React.createRef();
    this.action = this.action.bind(this);
  }

  action(e) {
    e.preventDefault();
    this.my_csv_link.current.link.click();
  }

  render() {
    return (
    <div>
      <button onClick={this.action}>
        ExportTest
      </button>
      <ReactCSV.CSVLink ref={this.my_csv_link} data="test"/>
    </div>
    );
  }
}

const domContainer = document.querySelector('#container');
ReactDOM.render(FileReaderElement(FileReader), domContainer);

I am trying to click the CSVLink once indirectly from a button click. However I get the following error in the browser console:

Uncaught TypeError: Cannot read property 'click' of undefined

I have tried

 this.my_csv_link.current.link.click(); (Cannot read property 'click' of undefined)
 this.my_csv_link.link.click(); (Cannot read property 'click' of undefined)
 this.my_csv_link.click(); (this.my_csv_link.click is not a function)
 this.my_csv_link.current.click(); (this.my_csv_link.current.click is not a function)

with no success

I followed this documentation article: https://reactjs.org/docs/refs-and-the-dom.html and this similar example https://stackoverflow.com/a/53558566/1238675 to build my code.

What am I doing wrong?

1
  • github.com/react-csv/react-csv/blob/master/src/components/… I don't a straight forward way to attach any ref or otherwise invoke any of the internal click handlers. An internal ref is attached (this.link) exists but this isn't used nor is it exposed out. You may be able to query the anchor tag to get a reference to the DOMNode and invoke a click event on that. Commented Jul 29, 2020 at 15:44

2 Answers 2

0

Nothing I tried was working, so instead I gave the CSVLink component an id and I traditionally just did

document.getElementById("CSVLink").click()

Sign up to request clarification or add additional context in comments.

Comments

0

I have a similar situation, the only way I could manage to trigger a click via ref was to use

ReactDOM.findDOMNode()

This is several lines of additional code, an additional import and seems likely to be less efficient, but I do not know if there are any benefits to this approach other than it is not using getElementById.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.