Home > Enterprise >  How to render an HTML element in React?
How to render an HTML element in React?

Time:12-17


function getElement(){
  const el = document.createElement('canvas');
  el.drawImage(...);
  ...
  return el;
}

function App() {
  const canvasRef = React.useRef(null);

  React.useEffect(()=>{
    const canvasEl = getElement(); // It returns HTMLCanvasElement
    document.body.append(canvasEl); // It works but it isn't my desired
    canvasRef.current = canvasEl; // It doesn't work
  }, []);
  
  return (
    <div><canvas ref={canvasRef} /></div>
  )

}

It is simplified code so my actual code is much more complicated.

How can I inject HTMLCanvasElement into ref?

CodePudding user response:

You can do something like this

import React from 'react';

function App() {
  const canvasRef = React.useRef(null);

  function addImageToElement() {
    const el = canvasRef.current;
    const ctx = el.getContext('2d');

    var img = new Image();
    img.src = 'https://picsum.photos/300';
    img.addEventListener(
      'load',
      () => ctx.drawImage(img, 10, 10, 150, 180),
      false
    );
  }

  React.useEffect(() => {
    addImageToElement();
  }, []);

  return (
    <div>
      <canvas ref={canvasRef} />
    </div>
  );
}

export default App;

Here is the live example: Edit interesting-kowalevski-7koui

function getCanvas() {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "green";
  ctx.fillRect(10, 10, 100, 100);
  return canvas;
}

export default function App() {
  const divRef = useRef(null);

  useEffect(() => {
    divRef.current.appendChild(getCanvas());
  }, []);

  return <div ref={divRef} />;
}

You don't have to create a new canvas element as you already have a canvas element in your JSX.

Once the ref is assigned, you can update it as you want.

Edit sharp-monad-r1fgd

function updateCanvas(canvas) {
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "green";
  ctx.fillRect(10, 10, 100, 100);
}

export default function App() {
  const canvasRef = useRef(null);

  useEffect(() => {
    updateCanvas(canvasRef.current);
  }, []);

  return (
    <div>
      <canvas ref={canvasRef} />
    </div>
  );
}
  • Related