Find all elements with className in children prop

40 Views Asked by At

As the title explains, I would like to find all the elements in the children prop and perform an action on all of them, the children prop can includes elements, strings etc.:

const newChildren = Children.toArray(children).map((child) => {
  const isItem =
    isValidElement(child) &&
    child.props.className.includes('item');

  if (isItem) {
    console.log('is an item, do something with it');
  }

  return child;
});

Get the error:

Cannot read properties of undefined (reading 'includes')
1

There are 1 best solutions below

0
mbojko On

Looks as if a simple safe navigation operator would do the trick:

  const isItem =
    isValidElement(child) &&
    child.props?.className?.includes('item');