How to Specify Dynamic Tag Name in React?

If you want to specify a dynamic tag name (for example, based on a condition), then you can do the following:

  1. Use a String Variable;
  2. Use the React.createElement() Method.

Using a String Variable

If you're using JSX, you can simply create a variable and use that as the tag name. For example, you can create a dynamic React component name based on a condition like so:

const CustomTag = (someCondition) ? 'div' : 'Foo';

<CustomTag myProp="myValue">

Please note that in JSX, name for React components must begin with an uppercase letter, or contain a dot in the name. This is because lowercase tag names (without a dot in the name) are interpreted as HTML tags.

Using the React.createElement() Method

A JSX element is just syntactic sugar for calling React.createElement() — which has the following syntax:

React.createElement(type, [props], [...children])

You can simply pass the dynamic tag name as the first argument to the React.createElement() method (as it accepts a string tag name). For example:

const type = (someCondition) ? 'div' : 'Foo';
const props = { myProp: 'myValue' };

React.createElement(type, props, '...');

This is especially useful if you're not using JSX.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.