Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I render an `HTMLCanvasElement` in React?

I have a utility which produces a thumbnail for a video and returns it as an HTMLCanvasElement. I'd like to render that element in React, like so:

render () {
   return (
      <div className='video-thumbnail'>
         {this.props.videoThumbnailCanvas}
      </div>
   );
}

But when I try that, I get an error that:

Error: Objects are not valid as a React child (found: [object HTMLCanvasElement]).

What's a good way to do this? One idea is to do direct DOM manipulation from componentDidMount (e.g. React.getDOMNode(this).appendChild(this.props.videoThumbnailCanvas)), but that seems rather hack-like.

like image 360
allenrabinovich Avatar asked Mar 09 '23 14:03

allenrabinovich


1 Answers

I got the same problem and you can solve in 2 ways:

the easy way:

render () {
   const src = this.props.videoThumbnailCanvas.toDataURL();
   return (
      <div className='video-thumbnail'>
         <img src={src} />
      </div>
   );
}

the other way i like more (but is personal):

onComponentDidMount() {
  const element = document.getElementById('uniquePlaceHolderKey');
  element.parentNode.replaceChild(this.props.videoThumbnailCanvas, element);
}

render () {
   return (
      <div className='video-thumbnail'>
         <div id="uniquePlaceHolderKey" ></div>
      </div>
   );
}

This second solution lets you load a temp element that you will swap with your own painted canvas instance. I did not found a proper react solution to force the appending of a pre rendered canvas element. There are proper react methods to get an element of a component ( like this.findDomNode() ) that are preferable to getElementById since work on the component instance.

like image 64
AndreaBogazzi Avatar answered Mar 11 '23 04:03

AndreaBogazzi