Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
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 core Child 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

 Answers
16

You should not manually manipulate the dom. React makes the assumption that it's the only one changing the page, so if that assumption is false it may make changes which overwrite yours, or skip changes that it doesn't realize it needs to do.


Instead, you should set state, causing the component to rerender. Then render something that matches what you want the dom to look like.


const Parent = React.FunctionComponent = ()=> {
const childRef = useRef<HTMLHeadingElement>(null);
const [large, setLarge] = useState(false);

useEffect(() => {
if (childRef.current && childRef.current.clientHeight > 30) {
setLarge(true);
}
}, []);

return (
<React.Fragment>
<Child ref={childRef}>hello world</Child>
{large && (<div className={someStyle}>hello</div>)}
</React.Fragment>
)
};

P.S: If you see the screen flicker with this code, consider changing it to useLayoutEffect instead of useEffect


[#3314] Monday, June 29, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
griffinr

Total Points: 242
Total Questions: 91
Total Answers: 105

Location: Indonesia
Member since Wed, Jul 7, 2021
3 Years ago
griffinr questions
Sat, Jul 18, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
Wed, Jun 5, 19, 00:00, 5 Years ago
;