React.cloneElement returning double elements when trying to validate a child element

288 Views Asked by At

I'm trying to pass props from Parent ("Section") element to all Children elements while trying to make sure that only "Block" elements can be used as children. It works fine when I use React.cloneElement the following way:

const Blocks = React.Children.map(children, child => {
      return React.cloneElement(child, {
        type: this.props.type,
      });
    });

But when add the validation the following way:

const Blocks = React.Children.map(children, child => {
      if (child instanceof Block) {
        return React.cloneElement(child, {
          ...this.props,
        });
      } else {
        console.log('not a block');
        console.log(child);
      }
    });

No content shows up at all. But when I use the validation code the following way:

const Blocks = React.Children.map(children, child => {
      if (child instanceof Block) {
        return React.cloneElement(child, {
          ...this.props,
        });
      } else {
        console.log('not a block');
        console.log(child);
      }
    });

But when I do it the following way, all elements show up double/twice:

const Blocks = React.Children.map(children, child => {
  if (child.type === Block) {
    return React.cloneElement(child, {
      ...this.props,
    });
  } else {
    console.log('not a block');
    console.log(child);
  }
});

As this output image:

screenshot

I'm pretty new to this. Not sure what I'm doing wrong here. Any help on this will be appreciated. Thanx.

0

There are 0 best solutions below