UNPKG

1.52 kBJavaScriptView Raw
1import {patch} from './patch'
2import {h} from './h'
3
4/**
5 * Function to throw error message when attempting to insert Fragement tag directly into DOM.
6 */
7function FragmentError() {
8 this.message = 'Cannot insert Fragment tag directly into DOM.'
9 this.toString = function() {
10 return this.message
11 }
12}
13
14/**
15 * @description A function to create and inject a virtual node into the document. The node will be appended to the container. The first argument can be either a JSX tag or an h function. After mounting, use the render function and the element returned by mount to udate the DOM.
16 * @example Insert Title tag into section:
17 * const title = mount(<Title message='Hello World!'/>, 'section').
18 * // Update the node with new prop value and reference to DOM from mount:
19 * render(<Title message='New stuff'/>, title)
20 * @param {function} tag A JSX tag or hyperscript function to render.
21 * @param {HTMLElement|boolean} [container] The element into which the tag will be rendered.
22 * @returns {HTMLElement} The base element of the rendered tag.
23 */
24export const mount = (tag, container) => {
25 container = typeof container === 'string' && document.querySelector(container)
26 if (!container) container = document.body
27 if (Array.isArray(tag)) throw new FragmentError()
28 const element = patch(tag)
29 if (tag.props && tag.props['onComponentDidMount']) {
30 tag.props['onComponentDidMount'].call(tag.props['onComponentDidMount'], element)
31 }
32 element.mounted = true
33 return container.appendChild(element)
34}