React JS-Return Multiple Element from `render()` function
In early React JS version, there is rules to return multiple DOM element which must be wrap in atleast one Root DOM element. Some time we don’t want to wrap multiple element with extra dom element. Such as if the address
field has sub fields like street, zipcode, house or more other things.
In react 16, there is functionality to return two or more element using array in render()
function.
In Figure 1.1, shows the react component, where multiple DOM element is wrapped in one root DOM element.otherwise, React throws error and suggest to wrap the multiple DOM element in one root DOM element.
You can open the Developer console. Then, you will see the output of react component, there is no extra div added to wrap the component. If we do not want to add extra div (other DOM element) for rendering component we have to use Fragment feature of react js. But in this article I am talking about another feature, returning array of elements in React JS.
Form line 3...10, i have added the react element which return array of element of address information.Lines 6...8, it returns multiple element using comma separated array.
The output is shown in figure 1.4 when the code is run.
Output of Array element Component
Now, you can see the output,there is no extra div wraps Address component.
Sample Project To Expose Array Elements Feature of React JS
For sample project purpose, lets say we are building a website which have menu bar with different items. Menu Items are different for public and authenticate mode. We are using Array of Element in React JS render() function. The sample code and its explanation is provided below:
From line 4...11, shows the MenuItem for authenticate mode.It is a stateless item, which return array of list item for menu.From line 13...18, shows another stateless component for menu item for public mode view.From line 20...45, React Component is created for Menu, using Array Components Feature of React JS, which render Menu List.
From line 23..25, auth state is added for changing menu item during changing the auth state.From line 27...29, function onAuthStateChange() is added, which will be fired on click of Auth Button. shown in lines 33...36.From line 37...42,shows the ternary conditional statement, which shows the <AuthMenuList /> if auth is true (means: Authentication mode) else shows <MenuList /> (means: Public Mode).
Output of Menu Page Using Array of Elements In React JS render() function.
In Figure 2.2, You can click on auth button, it will change state of auth. You can now see that menu Items are different during auth state changing. When seen in developer console, there is not extra div or extra dom element to wrap the whole component in React JS.