React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)
What are the possible return types of render method?
Below are the list of following types used and return from render method,
vbnet
1. **React elements:** Elements that instruct React to render a DOM node. It includes html elements such as `<div/>` and user defined elements.
2. **Arrays and fragments:** Return multiple elements to render as Arrays and Fragments to wrap multiple elements
3. **Portals:** Render children into a different DOM subtree.
4. **String and numbers:** Render both Strings and Numbers as text nodes in the DOM
5. **Booleans or null:** Doesn't render anything but these types are used to conditionally render content.
Code Example
tsx
import React, { Component, createPortal } from 'react';
class RenderReturnTypesDemo extends Component<{ type: string }> {
render() {
switch (this.props.type) {
// 1. React Element (JSX)
case 'element':
return <div className="card">Standard JSX Element</div>;
// 2. Arrays & Fragments
case 'fragment':
return (
<React.Fragment>
<li>Item A</li>
<li>Item B</li>
</React.Fragment>
);
// 3. Portals
case 'portal':
return createPortal(<div>Modal Content</div>, document.body);
// 4. String or Numbers (rendered as text nodes)
case 'text':
return 'Calculated Total: 42 units';
// 5. Booleans or null (renders nothing)
case 'none':
default:
return null;
}
}
}