TransWikia.com

check the type of the only child in react

Stack Overflow Asked on November 7, 2021

I want to check if a react element has only one child, and in case that is true and the type of that child is a specific type then inject a prop to it. The only safe way that I found to do it is this:

    Children.count(children) === 1
    ? Children.map(children, (c) =>
      c.type === FormRow
        ? cloneElement(c, { compact: c.props?.compact || true })
        : c
    )
    : children

It’s a bit cumbersome, and the not even clear. Why I’m using Children.map for a single child? Because that is the only safe way react provides to access the opaque children structure.
I read the react API and it is very sparse in terms of children manipulation, very few methods.
Is there any better more obvious way?

I can build an utility function like this:

const isSingleChildOfType = (type, children) => {
  const childrenArr = Children.toArray(children)
  return childrenArr.length === 1 && childrenArr[0].type === type
}

But I’m not sure of the implications of turning children into an array. Does it alter the original children or creates a new one?

One Answer

Have a read of this and this.

It is valid to use the .ToArray() method as you are doing, but you can also access the children using indexing like [0] to avoid your map.


Some docs also state:

When there is only a single child, this.props.children will be the single child component itself without the array wrapper. This saves an array allocation.

But I am unsure how true this is, worth testing with some console.logs in your case.

Answered by Luke Storry on November 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP