0

I'm trying to draw with Konva a rectangle when clicking a button

This is the code:

import * as React from 'react'
import Konva from 'konva'
import { Stage, Layer, Line, Text, Rect, Group} from 'react-konva'
import { Portal, Html } from 'react-konva-utils'

export default function W(props) {

  const toggleShown = () => {
    setShown(!shown)
    console.log("shown: ", shown)
  }

  return (
    <Stage
      x={stagePos.x}
      y={stagePos.y}
      width={window.innerWidth}
      height={window.innerHeight}
    >
     <Layer>
        <Html>

          <button onClick={toggleShown}>Click</button>
          {
            shown
            &&
            <p>Hello World!!!</p>
            &&

            <Stage>
              <Layer>
                  <Rect width={100} height={100} fill="white" draggable />
              </Layer>
            </Stage>
          }
        </Html>
     </Layer>
    </Stage>
  )
}

When clicking on the button during execution I get on the console log:

shown:  false
shown:  true

which is fine, but on the dark background I do not get the white rectangle.

What am I doing wrongly? How to make it work?

Raphael10
  • 2,508
  • 7
  • 22
  • 50

1 Answers1

1

Your example doesn't work because the inner Stage has no width/height. So, it is 0 by default.

    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <Html>
          <button onClick={toggleShown}>Click</button>
          {shown && <p>Hello World!!!</p> && (
            <Stage width={window.innerWidth} height={window.innerHeight}>
              <Layer>
                <Rect width={100} height={100} fill="black" draggable />
              </Layer>
            </Stage>
          )}
        </Html>
      </Layer>
    </Stage>

https://codesandbox.io/s/compassionate-proskuriakova-zymx22?file=/src/index.js:331-797

P.S. probably you should not put another Stage on top of original stage. Just display rectangle inside first stage:

 <Layer>
        <Html>
          <button onClick={toggleShown}>Click</button>
        </Html>
        {shown && <Rect width={100} height={100} fill="white" draggable />}
     </Layer>
lavrton
  • 18,973
  • 4
  • 30
  • 63