DEV Community

eccyan
eccyan

Posted on

Component just rendering component from props

I wrote the component this like:

import React from 'react';
import PropTypes from 'prop-types';

class Renderer extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return React.createElement(this.props.component, this.props);
  }

  static propTypes = {
    component: PropTypes.element.isRequired,
  };
}

export default Renderer;
Enter fullscreen mode Exit fullscreen mode

This component can be used like this:

import Renderer from './components/renderer'
import AwesomeComponent from './components/awesome_component'
import hoc from './components/awesome_hoc'

() => {
  render <Renderer component={hoc(AwesomeComponent)} />;
}
Enter fullscreen mode Exit fullscreen mode

The reason why I use <Renderer /> is I don't want using React.createElement in JSX.
And I should not define useless constants like this:

import Renderer from './components/renderer'
import AwesomeComponent from './components/awesome_component'
import hoc from './components/awesome_hoc'

() => {
  const HocComponent = hoc(AwesomeComponent);
  render <HocComponent />;
}
Enter fullscreen mode Exit fullscreen mode

Does anyone know the name of such this component?

Top comments (1)

Collapse
 
eccyan profile image
eccyan

I improved the example because the last example is hard to understand.