0

Is there a way in React to skip over rendering children? I have existing DOM nodes on a page that I'd just like to wrap in a React component.

My use case is rendering the frame but not the static contents, which are pre-existing DOM nodes.

Something like:

const Frame = (props) => ( <div class="frame"> <SkipRender>{props.children}</SkipRender> </div> ) 
6
  • 2
    Just don't add {props.children}? It's really unclear what you're asking Commented Jan 30, 2023 at 22:26
  • If you want to see them on the screen they need to be rendered at least once. If you mean they are static elements on a page and you don't want to re-render them when dynamic neighbors change, then break them out into their own component. Commented Jan 30, 2023 at 22:41
  • I'd like to render around existing DOM nodes that are already on the page. Commented Jan 31, 2023 at 4:09
  • @Matt, is it possible to share skipRender component file as well Commented Jan 31, 2023 at 4:22
  • 1
    What exactly do you mean by "render around"? Are you saying that you'd like to bring existing elements into your component? If so, for what purpose? You could certainly manipulate the existing DOM but I just can't fathom why Commented Jan 31, 2023 at 4:41

1 Answer 1

1

I'm guessing, when you say 'static children', you mean you don't want to rerender them? If so, then I have a solution for you.

React has a feature called memoization, which remembers a value and only updates it when the values it depends on (its 'dependencies') get updated. We can implement it through the useMemo() hook. A SkipRender component will look something like this:

function SkipRender(props) { const children = useMemo(() => { return props.children; }, []); return children; } 

What we're doing here is taking in the passed children elements, memoizing it (remembering its initial value), and keeping it static. The empty dependency array [] on the 4th line means children variable doesn't have any values it depends on, so it will not reevaluate its value. Since we're storing React elements to it, this will make it so those elements won't rerender after the initial render, even if the passed values change. Let me know if this helps, or if you need more clarification!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your response. I actually don't want to render <SkipRender> at all. Just leave the existing DOM as is. If I understand useMemo correctly, you need to still pass props.children in as React components. What I'm asking for is to leave the contents alone.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.