Say I have a component that should wrap a child component and use an IntersectionObserver to monitor when the child appears on screen, and then fade it in.
I could implement something like this:
function FadeIn(props: PropsWithChildren) {
const ref = useRef(null);
//Fade in logic
return <div ref={ref}>{props.children}</div>;
}
but this introduces an additional element, which may break something. I would prefer to be able to do this:
function FadeIn(props: PropsWithChildren) {
//Fade in logic
return <>{props.children}</>;
}
Here I use a fragment instead of a div, but fragments cant take a ref, so there's nothing I cant actually act on.
Essentially I'm looking for a non-intrusive way to implement a React wrapper Component that provides some functionality to its children, without disturbing the DOM or editing the child itself. Can this be done?
Here's an example of
Transitionusing React Transition GroupThis implementation would look something like this: (you can still insert a
refif needed,Transitiontakes arefprop.Note that the setup is different if you're forwarding a ref
Using the
transitionStatewould then allow you to style it in your own preferred wayThe available states are defined as:
This example uses
"react-transition-group": "^4.3.0", and the types from"@types/react-transition-group": "^4.2.3"; there are likely newer versions of this package but some of this may still apply.