Recurse on the node: a string is text, an object is <type attrs>children</type>. Then make it correct HTML: escape text and attribute values (otherwise user content becomes markup), write void elements like <img> and <br> without a closing tag, treat true props as bare boolean attributes and drop false/null, skip event handlers, map className to class and turn a style object into CSS (camelCase to kebab-case, px on plain numbers except unitless properties). The React-like extras: function components called with their props, fragments, arrays from map, false/null children rendering nothing, and raw HTML only through dangerouslySetInnerHTML.
React-like VDOM but instead of creating DOM nodes, output an HTML string given an input object with type and attributes.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
A string renders as itself; an element renders its opening tag with each prop as name="value", then its children recursively, then the closing tag. This works for trusted, simple trees, but it's an injection hole: nothing is escaped.
// { type, props, children } to HTML. Text children are strings; element children are nodes.function renderToString(node) {if (typeof node === 'string') return node;const { type, props = {}, children = [] } = node;const attrs = Object.entries(props).map(([name, value]) => ` ${name}="${value}"`).join('');return `<${type}${attrs}>${children.map(renderToString).join('')}</${type}>`;}
passes 3 checks run on every build, against the native method where there is one
- elements, attributes and text
- nested several levels
- no children
Escape & < > " ' in text and attribute values. Void elements (img, br, input…) can't have content or an end tag. In JSX disabled={true} means a bare disabled, and false/null mean the attribute is absent; onClick and other handlers have no HTML form. className and htmlFor exist because class and for are reserved words; a style object becomes margin-top:8px, with px added to plain numbers except unitless properties like opacity and zIndex. Children that are false, null, undefined or true render nothing, which is what {cond && <X/>} relies on.
const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ESC[c]);// Elements that never have content or a closing tag.const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);// CSS properties that take plain numbers; other numbers get "px", as React does.const UNITLESS = new Set(['opacity', 'zIndex', 'fontWeight', 'lineHeight', 'flex', 'flexGrow', 'flexShrink', 'order', 'zoom']);function styleToString(style) {return Object.entries(style).filter(([, v]) => v != null && v !== '').map(([key, v]) => {const prop = key.startsWith('--') ? key : key.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase());const value = typeof v === 'number' && v !== 0 && !UNITLESS.has(key) ? `${v}px` : v;return `${prop}:${value}`;}).join(';');}function attributes(props) {let out = '';for (const [name, value] of Object.entries(props)) {if (name === 'children' || name === 'key' || /^on[A-Z]/.test(name)) continue; // events don't serialiseif (value == null || value === false) continue; // absentconst attr = name === 'className' ? 'class' : name === 'htmlFor' ? 'for' : name;if (value === true) out += ` ${attr}`; // boolean attribute: present means trueelse if (name === 'style' && typeof value === 'object') out += ` style="${escapeHtml(styleToString(value))}"`;else out += ` ${attr}="${escapeHtml(value)}"`;}return out;}function renderToString(node) {if (node == null || typeof node === 'boolean') return ''; // {cond && <x/>} leaves false behindif (typeof node === 'string' || typeof node === 'number') return escapeHtml(node);const { type, props = {}, children = [] } = node;const open = `<${type}${attributes(props)}>`;if (VOID.has(type)) return open;return `${open}${children.map(renderToString).join('')}</${type}>`;}
passes 5 checks run on every build, against the native method where there is one
- text and attribute values are escaped
- void elements have no closing tag
- booleans, null and event handlers
- className, htmlFor and style objects
- numbers render; false, null and undefined children render nothing
If type is a function, it's a component: call it with its props plus children and render what it returns. A Fragment renders only its children, and arrays (from items.map) render in sequence; key is for reconciliation and never reaches the HTML. Raw HTML is allowed only through dangerouslySetInnerHTML: { __html }, so the unsafe path is explicit. Tag names are validated so a malicious type can't inject attributes.
const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };const escapeHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ESC[c]);// Elements that never have content or a closing tag.const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);// CSS properties that take plain numbers; other numbers get "px", as React does.const UNITLESS = new Set(['opacity', 'zIndex', 'fontWeight', 'lineHeight', 'flex', 'flexGrow', 'flexShrink', 'order', 'zoom']);function styleToString(style) {return Object.entries(style).filter(([, v]) => v != null && v !== '').map(([key, v]) => {const prop = key.startsWith('--') ? key : key.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase());const value = typeof v === 'number' && v !== 0 && !UNITLESS.has(key) ? `${v}px` : v;return `${prop}:${value}`;}).join(';');}function attributes(props) {let out = '';for (const [name, value] of Object.entries(props)) {if (name === 'children' || name === 'key' || /^on[A-Z]/.test(name)) continue; // events don't serialiseif (value == null || value === false) continue; // absentconst attr = name === 'className' ? 'class' : name === 'htmlFor' ? 'for' : name;if (value === true) out += ` ${attr}`; // boolean attribute: present means trueelse if (name === 'style' && typeof value === 'object') out += ` style="${escapeHtml(styleToString(value))}"`;else out += ` ${attr}="${escapeHtml(value)}"`;}return out;}const Fragment = Symbol('Fragment');// Adds components, fragments, nested arrays and raw HTML, the way React's renderToString handles them.function renderToString(node) {if (node == null || typeof node === 'boolean') return '';if (typeof node === 'string' || typeof node === 'number') return escapeHtml(node);if (Array.isArray(node)) return node.map(renderToString).join(''); // lists from .map()const { type, props = {}, children = [] } = node;if (typeof type === 'function') return renderToString(type({ ...props, children })); // a componentif (type === Fragment) return renderToString(children);if (typeof type !== 'string' || !/^[a-zA-Z][a-zA-Z0-9-]*$/.test(type)) throw new TypeError(`invalid element type: ${String(type)}`);const { dangerouslySetInnerHTML, ...rest } = props;const open = `<${type}${attributes(rest)}>`;if (VOID.has(type)) return open;// Raw HTML only through an explicitly dangerous prop, as in React.const inner = dangerouslySetInnerHTML ? dangerouslySetInnerHTML.__html : renderToString(children);return `${open}${inner}</${type}>`;}
passes 6 checks run on every build, against the native method where there is one
- function components get props and children
- lists from map, and keys don't appear
- fragments render only their children
- raw HTML only through dangerouslySetInnerHTML
- an invalid tag name throws instead of injecting markup
- components compose
Server-side rendering
renderToString in react-dom/server does this for a React tree so the server can send HTML that shows before JavaScript loads; the client then hydrates it.
Why escaping is the default
React escapes every string it renders, which is why injecting markup takes the deliberately named dangerouslySetInnerHTML.
Hydration mismatches
If server HTML and the first client render differ (a timestamp, Math.random(), browser-only data), React warns about a hydration mismatch. A renderer like this one is the server half of that contract.
Not escaping text or attribute values: a user's name becomes a script tag.
Writing
<img></img>or<br></br>.Rendering
disabled="false", which still disables the element: boolean attributes are about presence.Printing
falseornullchildren as text.Serialising
onClickas an attribute.
How would you stream the output?
Make the renderer a generator that yields the opening tag, then each child's chunks, then the closing tag, and write chunks to the response as they come. React's renderToPipeableStream does this so the browser can start parsing early.
How do you make the client reuse this HTML?
Hydration: render the same tree on the client and attach event handlers to the existing nodes instead of creating new ones. Both renders must produce the same markup.
Why validate tag names?
The tag is written into the markup unescaped. A type like 'div onclick=alert(1)' would inject an attribute; only [a-zA-Z][a-zA-Z0-9-]* is safe.
- html.spec.whatwg.org/multipage/syntax.html#void-elements
- developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML
- react.dev/reference/react-dom/server/renderToString
- react.dev/reference/react-dom/components/common#applying-css-styles
- cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html