Search code examples
reactjskonvajsreact-konva

React Konva center text in square


I am trying to create a button with some text centred using a Rect and a Text component.

Here is a piece of code:

        <Stage>
            <Layer>
                <Rect
                    x={window.innerWidth - 50}
                    y={window.innerHeight - 50}
                    width={30}
                    height={30}
                    fill='#f2f1f0'
                    stroke='#777'
                    strokeWidth={1}
                >
                <Text
                  fontSize={20}
                  text="+"
                  stroke='#777'
                  strokeWidth={1}
                  align="center"
                />
               <Rect />
            </Layer>
        </Stage>

But I got this error :

Uncaught (in promise) TypeError: parentInstance.add is not a function

Is there a right way to put the Text component inside the Rect component?


Solution

  • Try this:

    const App = () => {
      const textRef = React.useRef();
      const [size, setSize] = React.useState({ x: 0, y: 0 });
      React.useEffect(() => {
        setSize({
          width: textRef.current.width(),
          height: textRef.current.height()
        });
      }, []);
      return (
        <Stage width={window.innerWidth} height={window.innerHeight}>
          <Layer>
            <Group x={20} y={50}>
              <Rect
                  x={window.innerWidth - 50}
                  y={window.innerHeight - 50}
                  width={size.width}
                  height={size.height}
                  fill='#f2f1f0'
                  stroke='#777'
                  strokeWidth={1}
              />
              <Text
                ref={textRef}
                fontSize={20}
                text="+"
                stroke='#777'
                strokeWidth={1}
                align="center"
              />
            </Group>
          </Layer>
        </Stage>
      );
    };