import { storiesOf } from '@storybook/react'; import React, { forwardRef, useRef, useState, useEffect, MutableRefObject } from 'react'; import { useEnsuredForwardedRef } from '../src'; import ShowDocs from './util/ShowDocs'; import { boolean, withKnobs } from '@storybook/addon-knobs'; const INITIAL_SIZE = { width: null, height: null, }; const Demo = ({ activeForwardRef }) => { const ref = useRef(null); const [size, setSize] = useState(INITIAL_SIZE); useEffect(() => { handleClick(); }, [activeForwardRef]); const handleClick = () => { if (activeForwardRef) { const { width, height } = ref.current.getBoundingClientRect(); setSize({ width, height, }); } else { setSize(INITIAL_SIZE); } }; return ( <>
Parent component using external ref: (textarea size)
{JSON.stringify(size, null, 2)}
); }; const Child = forwardRef(({}, ref: MutableRefObject) => { const ensuredForwardRef = useEnsuredForwardedRef(ref); const [size, setSize] = useState(INITIAL_SIZE); useEffect(() => { handleMouseUp(); }, []); const handleMouseUp = () => { const { width, height } = ensuredForwardRef.current.getBoundingClientRect(); setSize({ width, height, }); }; return ( <>
Child forwardRef component using forwardRef: (textarea size)
{JSON.stringify(size, null, 2)}
You can resize this textarea: