My parent component looks like:
export const ParentComponent = (props: ParentProps) => {
const [visible1, setVisible1] = React.useState<boolean>(false);
const [visible2, setVisible2] = React.useState<boolean>(false);
const [visible3, setVisible3] = React.useState<boolean>(false);
return (
<Wrapper>
<button onClick={() => setVisible1(true)}>hello</button>
<button onClick={() => setVisible2(true)}>hello</button>
<button onClick={() => setVisible3(true)}>hello</button>
<SubWrapper>
{visible1 ? <ChildComponent1 begin={visible1}/> : null}
{visible2 ? <ChildComponent2 begin={visible2}/> : null}
{visible3 ? <ChildComponent3 begin={visible3}/> : null}
</SubWrapper>
</Wrapper>
)
}
I tried using const ref = React.useRef(null) within my child components but given that they're not rendered yet and have a possibility of being 'null', I get an error object is possibly 'null'.ts(2531)
interface BeginProps {
begin: boolean
}
export const ChildComponent1 = (props:BeginProps) => {
const [height, setHeight] = React.useState<string>('0px')
const contentRef = React.useRef(null)
React.useEffect(() => {
setHeight(contentRef.current.clientHeight) // here's where the error comes
}, [props.begin])
return (
<>
<Line style={{height: `${height}`, top: '250px'}} />
<ContentWrapper ref={contentRef}> ... </ContentWrapper>
</>
)
}
even this is giving me the null possibility error
React.useEffect(() => {
if (contentRef.current != null) {
setHeight(contentRef.current.clientHeight) // here's where the error comes
}
}, [props.begin])
Is there any way to obtain child component height after they're rendered?
The reason I need this height is that the width of the screen changes on different devices, and I need the exact for a different dependent component which is positioned absolute.