In the reaction, can I display child components without a shell?

I want to make:

render: () -> {@props.children} 

This makes me do:

  render: () -> <div>{@props.children}</div> 

The reason I want to do the first is because the children provided have their own context based on the owner. But if I create them using the shell, then the element that is the parent does not have its context set. Then a warning is issued:

Owner and parent based contexts differ (values: undefined vs [object Object] ) for key (x)

This is discussed here: https://gist.github.com/jimfb/0eb6e61f300a8c1b2ce7

But no solution is proposed.

The warning occurs because the component that displays the child is the β€œowner” and it sets the context, but the div shell element is β€œparent” and has no context. My idea was to get rid of the div. But I can’t get rid of him.

+6
source share
3 answers

I used the following code to use the <span> wrapper for text :

 render() { if (!this.props.children) { return null; } else if (React.isValidElement(this.props.children)) { return this.props.children; } return <span>{this.props.children}</span>; } 
+3
source

In situations where one child is required:

 render() { return React.Children.only(this.props.children) } 

This is what reaction-reduction uses in connect() , FWIW.

+1
source

With React 16 =>

 render() { return <React.Fragment>{this.props.children}</React.Fragment>; } 

or

 render() { return <>{this.props.children}</>; } 
0
source

All Articles