Can I pass HTML tag as prop - React

JSX expressions must start with a cap, for example <Elment />

In your case, when you want to pass tag names, use createElement:

<div>
  {React.createElement(this.props.tag, {children: <content>, prop1: <v1>, ...})}
<div>

Another alternative will be to use recompose#componentFromProp


UPDATED:

Yes, we can pass HTML tag as a prop. There are several ways based on what you want.

  1. Passing tag as a prop
<ChildComponent tag="h1" />

And inside child component, we can use the tag as below.

const Child = ({ tag: Tag}) => (
    <Tag>Hello World</Tag>
)
  1. By setting dangerouslySetInnerHTML
<Child tags="<h1>Hello world</h1>" />

Inside child component:

const Child = props => <div dangerouslySetInnerHTML={{ __html: props.tags.outerHTML }}/>

Here is what you should know about dangerouslySetInnerHTML. In short, this exposes XSS attack.

This one is not related to passing as a prop. But you might wanna consider

If you are doing SEO task related (maybe nextjs) and you need to render conditional tag (sometimes h2 and sometimes h3). Then you can do as follow!

  1. Conditional Statement
// Parent
const Parent = () => <Child isH3Tag />
// Child
const Child = ({ isH3Tag = false, children }) => isH3Tag ? <h3>{children}</h3> : <h2>{children}</h2>;

Here is a demo. https://codesandbox.io/s/8x65l707yj

Tags:

Reactjs