user1526912
user1526912

Reputation: 17280

How to trigger hyperlink click even - react component

In my react component I am trying to trigger a click on the hyperlink created in the below function:

  getUsers(e){
    e.preventDefault();
    const { userIds } = this.props;
    BatchRoleActions.getAllRoleUsers(userIds)
    .then((users) => {
      const link = document.createElement('a');
      link.setAttribute('id', 'csvLink');
      link.setAttribute('download', 'roles.csv');
      link.setAttribute('href', users);
      document.getElementById('csvLink').onClick();
    });

  }

When the function is run I get the below error : Uncaught (in promise) TypeError: Cannot read property 'onClick' of null

How can I trigger click to start my download?

BatchRoleActions.getAllRoleUsers(userIds) returns an an array with data for export to a csv file. encodeURI(data:text/csv;charset=utf-8,\uFEFF${data});

I am trying to find a solution for: ReactJs - How to complete onClick before download - href

Upvotes: 0

Views: 1787

Answers (1)

Raghudevan Shankar
Raghudevan Shankar

Reputation: 1093

Edit1: I misunderstood what the OP asked for, edited my answer now!
Edit2: More edits after reading OP's link

I've set up a sandbox to mock what you're trying to do; take a look at it here - https://codesandbox.io/s/18k6oppy2l

Pay attention to the Users.js file

  1. We'll put a visible button and an invisible <a> tag in the DOM

  2. When the user clicks on the Download User data button, the request to retrieve the users is made

  3. Once the request resolves to string representation of the users data, we call setState to set the user in the state

  4. In the setState callback, we then programatically "click" the invisible <a> tag to download the users.csv; this will trigger the download of the file

Upvotes: 1

Related Questions