user7023664
user7023664

Reputation:

Can I pass HTML tag as prop - React

I want to do something like this.

In the parent component

<child tag={h1}/>

In the child component

<this.props.tag />

The problem "Unresolved variable or type div" throwing When i pass one of html components ( tags ) like ( div , h1, ext. )

Upvotes: 15

Views: 14865

Answers (3)

Karan Rohra
Karan Rohra

Reputation: 11

You can pass tag as children, from parent Component like this:
In the parent component:

<Child> <h1></h1> </Child>

In the child component you can access like:


 render() {
    return (
       {this.props.children}
    )
}

Upvotes: 0

Kyaw Siesein
Kyaw Siesein

Reputation: 725

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

Upvotes: 32

Meir
Meir

Reputation: 14375

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

Upvotes: 4

Related Questions