[Vuejs]-How to allow HTML templates define React components the same as Vue?

0👍

I dont see the point in using React if you want vue/angular-like templates, use vue instead. React uses javascript xml or jsx if you will, whichs do look like templates but are actually giving you the benefit of everything javascript can do.

Although, if you want everything in a single component, there’s nothing stopping you from doing so.

now if you meant that you want a single component that renders all children, you aren’t far off tbh. Here’s a simple example from codeburst

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}


render () {
  return (
    <div className='container'>
      <Picture src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

0👍

React is not template-based but uses JS or JSX to define components, so options are limited.

It’s preferable to

It’s possible to render HTML snippets with dangerouslySetInnerHTML:

<div dangerouslySetInnerHTML={this.props.kids}/>

This doesn’t allow to use custom components inside snippets because React components don’t use selectors. It may be possible to parse a template with HTML parser to a hierarchy of React elements and then replace custom elements like <some-component> with corresponding React components, like shown in this question.

It’s possible to define and transpile components on the fly but this isn’t recommended in production:

<script src="https://unpkg.com/babel-standalone/babel.js"></script>
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script type="text/babel">
  var Foo = () => 'Foo';
</script>
...
<script type="text/babel">
  ReactDOM.render(<Foo/>, document.getElementById('foo'));
</script>

In order to use context API for multiple components, they should be rendered not as root components with render but within a common parent, for instance, as portals with createPortal:

...
<script>
  var portals = {};
</script>
...
<script type="text/babel">
  portals['#foo'] = <Foo/>;
</script>
...
<script type="text/babel">
  // runs on page load
  var CommonContext = ...;
  var Root = () => (
    <CommonContext.Provider value={...}>
      {Object.entries(portals).map(({ selector, child }) => (
        ReactDOM.createPortal(child, document.querySelector(selector))
      )}
    </CommonContext.Provider>      
  );

  ReactDOM.render(<Root/>, document.getElementById('root'));
</script>

Leave a comment