ReactJS: create element with custom type programatically?

Viewed 232

Is it possible to do this thing with JSX?

function Header(props) {
  return React.createElement(props.element, {}, 'Hello world!');
}

So the return can be h1, h2, h3, or any depends on the props. Is it possible to do the same with JSX?

2 Answers

Sort of, but not without a variable assignment of some sort.

Since

  • <h1 /> compiles to React.createElement("h1", null);
  • <Thing /> compiles to React.createElement(Thing, null);

you can essentially "cheat" the machinery to use your dynamic prop as the element type:

function Header(props) {
  const Element = props.element;  // This variable name _must_ be in PascalCase.
  return <Element>Hello world</Element>;
}

compiles to

function Header(props) {
  var Element = props.element;
  return React.createElement(Element, null, "Hello world");
}

which does what you'd expect. However, if Element is in lower-case, it doesn't work since lower-case JSX tag names are assumed to map to HTML/SVG tags and are transformed into strings:

function Header(props) {
  const element = props.element;
  return <element>Hello world</element>;
}

compiles to

function Header(props) {
  var element = props.element; // This is unused.
  return React.createElement("element", null, "Hello world");
}

Yes it is possible;

function Header(props) {
  return <props.element>Hello world!</props.element>;
}

function App(){
 return (
  <div>
    <Header element='h1' />
    <Header element='h2' />
    <Header element='h3' />
  </div>
 );
}

function Header(props) {
  return <props.element>Hello world!</props.element>;
}

ReactDOM.render(<App/>, root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Related