Reputation:
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
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
Reputation: 725
UPDATED:
Yes, we can pass HTML tag as a prop. There are several ways based on what you want.
<ChildComponent tag="h1" />
And inside child component, we can use the tag as below.
const Child = ({ tag: Tag}) => (
<Tag>Hello World</Tag>
)
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!
// 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
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