Skip to content
Advertisement

React – How can I strip top level div from a React.Component

When writing JSX, I sometimes need to create a top level element so the code will compile. For example, this won’t compile.

JavaScript

But this will:

JavaScript

Usually wrapping other React elements in a <div> works fine, but not always. So I’d like to know if I was forced to create a top level element to get the code to compile, can I later strip it off? If so how?

Below is a conceptual example of a problem I ran into with React router’s Switch element.

JavaScript

I provide this simplified example code so readers can understand what I’m asking.

I’m looking to get an answer to the question, not for a work around.

The question is: How can I get the children of a given react/JSX element? How can I change the stripDivFrom() function so that it works.

NOTE: The stripDivFrom() function currently doesn’t work. The Children property doesn’t is undefined (when I observe it in Chrome debugger). I found it when looking at the React source code but I’m obviously misunderstanding something. The browser console has an error that says: Uncaught TypeError: Cannot read property ‘toArray’ of undefined.

Updated

EDITED: After this question was asked, in React introduced a better solution to this problem.

In React 16.2.0 the component <React.Fragment> was added which solves this problem.

The following is how the code would now loook:

JavaScript

Advertisement

Answer

It will be available by element.props.children.

Write it like this:

JavaScript

What is props.children in react?

In JSX expressions that contain both an opening tag and a closing tag, the content between those tags is passed as a special prop: props.children.

React elements are basically objects, check this example:

JavaScript

Object created by react will be:

JavaScript

Check this: JSX Represents Objects

Working Code (style on wrapper div will not reflect in ui):

JavaScript
JavaScript

working Fiddle: https://jsfiddle.net/mayankshukla5031/0cwueg7j/

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement