How to create HTML opening and closing tab from a variable in React JS

Viewed 34

I am building a Web application using React JS. In my React JS code, I need to render the variable as opening and closing html tags. Let's say I have a variable as follow.

const tag = "div";

I want to render something like this:

<{tab}>Content</{tag}>

How can I do that?

1 Answers

You could use a switch to determine how to render given a tag type.

function Tag({ type, children }) {
   switch (type) {
     case "div":
       return <div>{children}</div>;
     case "ul":
       return <ul>{children}</ul>;
     case "nav":
       return <nav>{children}</nav>
     default:
       return <>{children}</>
   } 
}

<Tag type="div">Content</div>

An alternative and sketchier solution depending on your use-case that is much more dynamic but much less safe:

<div dangerouslySetInnerHTML={{ __html: `<${tag}>Content</${tag}>` }}></div>
Related