I want to upload a svg file and show preview in react, but I don't know how to convert a svg file into react component. I try to use DOMParser
to parse svg-xml string to Dodument Object, but it is not working.
import { useState } from 'react';
import { Upload, Button, Card } from 'antd';
import { UploadChangeParam } from 'antd/lib/upload/interface';
import 'antd/dist/antd.css';
function App() {
const [svgs, setSvgs] = useState<Document[]>([]);
const handleChange = async ({ file }: UploadChangeParam) => {
console.log(file);
let domparser = new DOMParser();
const svg = (await file.originFileObj?.text()) ?? '';
const ele = domparser.parseFromString(svg, 'image/svg xml');
setSvgs([...svgs, ele]);
};
return (
<div style={{ margin: 50 }}>
<Upload name="file" showUploadList={false} onChange={handleChange}>
<Button>Upload</Button>
</Upload>
{/* preview list */}
<Card style={{ marginTop: 20 }}>
{svgs.map((SVGComponent) => {
return <SVGComponent />;
})}
</Card>
</div>
);
}
export default App;
CodePudding user response:
You can use following library to convert svg's. You can also add its cli commands to your package.json