Reputation: 69
I am trying to learn to use react and typescript. However, I am really stuck here.
I am trying to download the text data from a card using a download button in json format. So far my code looks like this:
App.tsx
import React,{useState} from 'react';
import Tooltip from "@material-ui/core/Tooltip";
export const MyCard = () => {
const classes = useStyles();
return (
<Card className={classes.root}>
<CardHeader
title="My React Typescript App"
subheader="Aug 16, 2021"
/>
<IconButton>
<Tooltip title={"Download content"}>
</Tooltip>
</IconButton>
</Card>
);
I want to be able to download the title and subheader in json format when I click on the button. How can I do that?
Upvotes: 0
Views: 1398
Reputation: 76
Simply use below function to download JSON.
const Demo = () => {
const [cardTitle, setCardTitle] = useState('My React Typescript App');
const [cardSubTitle, setCardSubTitle] = useState('Aug 16, 2021');
const DownloadJSON = Data => {
const dataStr =
'data:application/json;charset=utf-8,' +
encodeURIComponent(JSON.stringify(Data));
const download = document.createElement('a');
download.setAttribute('href', dataStr);
download.setAttribute('download', 'CardData' + '.json');
document.body.appendChild(download);
download.click();
download.remove();
};
return (
<Card>
<CardHeader title={cardTitle} subheader={cardSubTitle} />
<Tooltip title="Delete">
<IconButton
aria-label="delete"
onClick={() => {
DownloadJSON({ cardTitle, cardSubTitle });
}}
>
Download content
</IconButton>
</Tooltip>
</Card>
);
};
Upvotes: 1