'how to export the return table data to a csv file using react js

I am new to React js.

I am trying to export the returned tabular data to a csv file on a button click.

let names = [
  {firstName: 'John',lastName: 'Cena'},
  {firstName: 'Rey',lastName: 'Mysterio'},
]

const App = props => {
  return (
    <div>
      {names.length > 0 && <table> //table renders only when array has elements 
        <tbody>
        <tr>
        <th>First Name</th>   //setting headers
        <th>Last Name</th>
        </tr>
        {names.map((name,index) => {       //mapping for individual rows
          return (
            <tr key={index}>
              <td>{name.firstName}</td>
              <td>{name.lastName}</td>
            </tr>
          )
        })}
        </tbody>
      </table>}
    </div>
  );
};

I want to create a button called export, and it should then download the table data thats being returned to a csv file.

Any help is greatly appreciated. Thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source