Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there a way to use a non-rendered React component? #41

Closed
pthieu opened this issue Aug 17, 2023 · 2 comments
Closed

Is there a way to use a non-rendered React component? #41

pthieu opened this issue Aug 17, 2023 · 2 comments

Comments

@pthieu
Copy link

pthieu commented Aug 17, 2023

I would like to take a list of data and render it in the background to generate images.

I have an array of data like this:

const data = [
  {
    height: 500,
    weight: 500,
    color: "#ff0000",
    text: "Hello World",
  },
  ...
];

I would like to loop through each item in the array and pass the data into a React element like:

for (const d of data) {
  const dataUrl = await domToBlob(<Component {...d} />);
  // upload to server
}

Is this possible?

@pthieu pthieu changed the title Is there a way to pass in a React component? Is there a way to use a React component? Aug 17, 2023
@pthieu pthieu changed the title Is there a way to use a React component? Is there a way to use a non-rendered React component? Aug 17, 2023
@qq15725
Copy link
Owner

qq15725 commented Aug 17, 2023

const container = document.createElement('div')
container.style.opacity = '0'
container.style.position = 'fixed'
document.body.appendChild(container)

const root = document.createElement('div')
container.appendChild(root)

const reactRoot = ReactDOM.createRoot(root)
//              👇🏻
reactRoot.render(<div ref={ onDidMount }>Hello, world</div>)

function onDidMount() {
  modernScreenshot.domToPng(root).then(dataUrl => {
    const link = document.createElement('a')
    link.download = 'screenshot.png'
    link.href = dataUrl
    link.click()
  })
}

https://codepen.io/qq15725/pen/PoXYyBe

@pthieu
Copy link
Author

pthieu commented Aug 17, 2023

thanks, had to modify slightly but this works
migrating over to this library!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants