Write a tiny renderElement(element, container) that turns elements into DOM
Write renderElement(element, container): a renderer like the first root.render, with no state and no updates. It replaces whatever container holds with DOM nodes built from element. Elements are what JSX makes: objects with a type and props, where props.children may be missing, one child, or an array (maybe nested).
A string or number becomes a text node, never parsed as HTML. null, undefined, true, and false render nothing. When type is a string, create that DOM element and set its props: children is rendered inside it, onClick and other on props become event listeners, a style object sets inline styles, props the DOM element has as properties (like className, htmlFor, value) are set as properties, and any other prop, like aria-label or data-id, as an attribute. When type is a function, call it with the props and render what it returns.
function Badge({ count }) {
return <span className="badge">Cart: {count}</span>;
}
renderElement(
<p title="Basket">
Items <Badge count={2} />
</p>,
document.getElementById("root"),
);
// <p title="Basket">Items <span class="badge">Cart: 2</span></p>
export function renderElement(element, container) {
// Replace container's content with DOM nodes for element.
}
- renders nested DOM elements and text
- sets properties like className and htmlFor, and other props as attributes
- renders numbers, including 0, and skips null, undefined, and booleans
- renders strings as text, never as HTML
- calls function components with their props, children included
- renders a component that returns null as nothing
- renders arrays of children made with map
- attaches event handlers and inline styles
- replaces what the container held
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…