1

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.

Da Moose
  • 111
  • 1
  • 14
  • https://stackoverflow.com/questions/27366077/only-allow-children-of-a-specific-type-in-a-react-component/36424582 check this once – Jayavel Jan 21 '19 at 05:25
  • Thanx but that didn't work. Actually, my issue is not that I can't validate a child, That part is working fine, but the issue is that when I'm getting the return, it's giving me back every element twice. Just as the screenshot I've provided above. – Da Moose Jan 21 '19 at 05:45
  • can you make a codepen / stackblitz on this – Jayavel Jan 21 '19 at 05:46
  • I quickly test out your code in a minimal setting & [it works fine](https://codesandbox.io/s/n0rlr878wj). Perhaps the problem is somewhere else in your code. – Derek Nguyen Jan 21 '19 at 08:37
  • Thanx. Your example is very helpful ... that works for me if I use specific props (like, type: this.props.type etc.), but as soon as I use `...this.props` everything doubles up again ... – Da Moose Jan 21 '19 at 11:31

0 Answers0