2

I am writing a webpage which dynamically renders elements from a database, with each one having its own state. To choose what element is rendered, I used a switch-case like this:

switch (this.state.type) {
  case 'textarea':
    element = <textarea {...this.state} />
    break

  ...

  default:
    element = <input {...this.state} />
}

What I would like to do is have a nice way of choosing which element is rendered, like this:

switch (this.state.type) {
  case 'textarea':
    tag = 'textarea'
    break

  ...

  default:
    tag = 'input'
}

element = <{tag} {...this.state} />

Is there a way to something similar to this in React?

2 Answers 2

3

You can use React.createElement [1], whose first argument is the element to render.

[1] https://reactjs.org/docs/react-api.html#createelement

Sign up to request clarification or add additional context in comments.

1 Comment

While this is true, I'd recommend against it. The doc you linked to says You will not typically invoke React.createElement() directly if you are using JSX So make sure you really need it before going crazy with it
1

You can already do that, the variable should start with an uppercase:

function getElementTag(type) {
  switch (type) {
    case 'textarea':
      return 'textarea'
    default:
      return 'input'
  }
}

function App() {
  const TagName = getElementTag('textarea');
  return (
    <div className="App">
      <TagName value="you can already do it" />
    </div>
  );
}

2 Comments

That is very cool. Thank you! But, why should the variable start with an uppercase? Is it just convention-wise?
It is a JSX convention so that it can differentiate between native HTML elements (lowercase) and React Components (capitalize) otherwise it will try and render a html tag called tagName straight into the browser.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.