Customizing the details of a dynamically created React component

I am refactoring some of my React code for ease of use in places where I cannot use Babel directly (for example, in short embedded JavaScript on pages). To help with this, I set up a short function that builds the components and passes them the details. This code works very well:

components.js:

import ResponsiveMenu from './components/responsive-menu';
window.setupMenu = (items, ele) => {
  ReactDOM.render(<ResponsiveMenu items={items}/>, ele);
}; 

static js.html:

<div id="menu"></div>
<script>
   setupMenu({ items: [] }, document.getElementById('menu');
</script>

However, when I try to turn it into something more general to handle more components, for example:

components.js:

import ResponsiveMenu from './components/responsive-menu';
import AnotherComp from './components/another-comp';

window.setupComponent = (selector, name, props) => {
  let eles;

  if (typeof selector == 'string') {
    eles = [];
    let nl = document.querySelectorAll(selector), node;
    for (let i = 0; node = nl[i]; i++) { eles.push(node); }
  } else {
    eles = $.toArray(selector); // A helper function that converts any value to an array.
  }

  return eles.map (
    (ele) => {
      let passProps = typeof props == 'function' ? props(ele) : props;
      return ReactDOM.render(React.createElement(name, passProps), ele);
    }
  );
};

static js.html:

<div id="menu"></div>
<script>
   setupComponent('#menu', 'ResponsiveMenu', { items: [] });
</script>

Then I get this error: Warning: Unknown prop "items" on <ResponsiveMenu> tag. Remove this prop from the element. For details, see (really unhelpful shortened link that SO doesn't want me posting)

Please help me understand why this works for the JSX version, and not for the more manual version of component creation.

+4
source share
1

string React.createElement, DOM html DOM ResponsiveMenu.

window.

:

// store component into window variable
window.components = {
     ResponsiveMenu: ResponsiveMenu
}

//extract component from window variable by name
React.createElement(window.components[name], passProps)
+4

Source: https://habr.com/ru/post/1659570/


All Articles