1

I am looking for a solution whereby data retrieved from the backend is written to a csv and downloaded to the clients pc triggered by an event on one of my react components. I have tried a few solutions with packages such as react-csv but I cannot get the async feature to work.

Any recommendations would be greatly appreciated.

1
  • Can you show the code you've tried so far? Commented Feb 3, 2018 at 17:08

1 Answer 1

2

Not sure what you mean by "async feature" but if you are just looking to create a CSV download, you can use a simple anchor tag with the download attribute like so:

  <a
    href=`data:text/csv,${encodeURI(your-csv-string)}`
    download=`your-file.csv`>

    Click to download
  </a>

If you need to hook into an event within a component you could do something along the lines of the following:

handleClick() {
  // Do some stuff (build the csv string?)

  // Initiate the download
  this.link.href = `data:text/csv,${encodeURI(your-csv-string)}`
  this.link.download = `your-file.csv`
  this.link.click()
}

render() {
  return (
    <div>
      // Create a hidden link with a ref you can use later
      <a ref={link => this.link = link}
        style={{display: 'none'}}
      />

      <button onClick={this.handleClick}>Click to download</button>
    </div>
  )  
}
Sign up to request clarification or add additional context in comments.

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.