14
rated 0 times
[
19]
[
5]
/ answers: 1 / hits: 9286
/ 4 Years ago, thu, july 2, 2020, 12:00:00
I would like to know if there is a way to append another react component to the useRef
element?
Scenario: when the Parent
's useEffect
detects the Child
's heading to be bigger than X size: add another react component.
- I would like the implementation to be on the
Parent
, because in my whole app, there was only one specific case where I need to do this. Therefore I did not want to modify the coreChild
component props.
import React, { ReactNode, useEffect, useRef } from 'react';
import { css } from 'emotion';
const someStyle = css`
background-color: red;
`;
type ChildProp = {
children: ReactNode;
};
const Child = React.forwardRef<HTMLHeadingElement, ChildProp>(
({ children }, ref) => {
return <h1>{children}</h1>;
},
);
const Parent = React.FunctionComponent = ()=> {
const childRef = useRef<HTMLHeadingElement>(null);
useEffect(() => {
if (childRef.current && childRef.current.clientHeight > 30) {
// append component to childRef.current
// e.g. childRef.current.append(<div className={someStyle}>hello</div>);
}
}, []);
return <Child ref={childRef}>hello world</Child>;
};
export default Parent;
More From » reactjs