프론트엔드 웹/React

React Image Component Export to PNG/JPEG/SVG

세리둥절 2023. 5. 3. 19:29
반응형

 

downloadjs와 html-to-image 라이브러리를 활용해서
React에서 만든 컴포넌트를
이미지 파일로 export 할 수 있다

 

 

import React, { useCallback, useRef } from 'react';
import Victory from './Victory';
import styled from '@emotion/styled';
import downloadjs from "downloadjs";
import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'html-to-image';


const Container = styled.div`
  display: 'flex';
`

const Image = styled.div`
  width: max-content;
  inline-size: max-content;
  height: max-content;
`
const App = () => {
  const ref = useRef<HTMLDivElement>(null)

  const handleClick = useCallback(async () => {
    if (ref.current) {
      downloadjs(await toJpeg(ref.current), "test.jpg");
      // downloadjs(await toSvg(ref.current), "test.svg");
    }
  }, []);

  return (
    <Container>
      <Image ref={ref}>
          <Victory/>
      </Image>
      <button onClick={() => handleClick()}>Click</button>
    </Container>
  );
}

export default App;

 

클릭 버튼을 누르면 test.jpg 라는 이름으로 JPG 파일이 다운로드된다! 대박

 

반응형