3

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 2

1

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");
}
1

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>

3
  • This is not what OP asked; they explicitly wanted to use JSX syntax, not React.createElement.
    – AKX
    Sep 17, 2021 at 8:19
  • @AKX oh yea, I forgot to refactor that function; thank you for pointing out
    – Mechanic
    Sep 17, 2021 at 8:22
  • 1
    owh, it doesn't need to be pascal case if it was in an object. thx
    – nouvist
    Apr 20, 2022 at 19:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.