Yes, you can — even with JSX if you'd like.
The trick is to understand how JSX is translated into the React.createElement
calls:
- bracketed text starting with a lowercase character is translated into a string:
<div/>
becomes React.createElement('div')
.
- bracketed text starting with an uppercase is assumed to be a variable in scope:
<SomeComponent/>
becomes React.createElement(SomeComponent)
.
Now imagine if you assign var SomeComponent = 'div'
. Then the uppercase rule would apply (passing the variable to createElement
), but it will have the same effect as the first rule (because the variable references a string)!
Here's how it can look in a practical situation:
let Child = ({EL,thing}) => <EL className="helper-thing">{{ thing.name }}</EL>
let ListParent = ({things}) => <ul>
{things.map(t => <Child EL='li' thing={t}/>)}
</ul>
let ArticleParent = ({things}) => <article>
{things.map(t => <Child EL='p' thing={t}/>)}
</article>
See the official docs on Choosing the Type at Runtime for a slightly different — perhaps cleaner — approach that capitalizes the property inside the child component.