For many React developers using JSX it is not clear how to make a dynamic JSX tag. Meaning that instead of hardcoding whether it is input or textarea or div or span (or anything else) we would like to keep it in a variable.

Let’s have a look.

const input = this.props.long ? <textarea
  onChange={this.props.onChange}
  className="make-this-pretty"
  id="important-input"
  name="important-input"
/> : <input
  onChange={this.props.onChange} 
  className="make-this-pretty"
  id="important-input"
  name="important-input"
/>;

As you can see there is a lot of duplication here. The only difference is that sometimes we want to use input and sometimes textarea. How can we do it? Quite simply it turns out.

const Tag = this.props.long ? "textarea" : "input"

const input = <Tag 
  onChange={this.props.onChange}
  className="make-this-pretty"
  id="important-input"
/>;

However it is required that your variable starts with uppercase instead of lowercase. Lowercase JSX tag names are directly compiled as strings. You can see the result of JSX compilation on the right column:

Original and compiled JSX code

That’s it. No magic :).

comments powered by Disqus