Skip to content

Instantly share code, notes, and snippets.

@emplums
Last active May 24, 2018 20:53
Show Gist options
  • Save emplums/5b5b628964a49ae677f2db372ddece58 to your computer and use it in GitHub Desktop.
Save emplums/5b5b628964a49ae677f2db372ddece58 to your computer and use it in GitHub Desktop.
dynamic tags
// Text component
const Text = ({ tag, fontSize, children}) => {
// This has to be set as Tag here because JSX wants the tag name to be capitalized, but it renders down to <h1> anyways
// Default to a <p> tag if no tag is set
const Tag = tag ? `${tag}` : 'p';
return <Tag className={classnames(fontSize ? `f${fontSize}` : null)}>{children}</Tag>
}
export default Text
// Heading component
import React from 'react'
import Text from './Text'
const Heading = ({ tag, children }) => (
<Text tag={tag}>{children}</Text>
)
export default Heading
// Usage
<Heading tag={'h1'}>
Heading
</Heading>
//DOM output
<h1>Heading</h1>
@emplums
Copy link
Author

emplums commented May 24, 2018

Here's an example of how we can dynamically change tags based on props. I personally prefer having the tag set in the props, just because it feels like it keeps the component API more uniform - anything that changes the presentation of a component is passed in via props. Users don't have to remember any exceptions to that rule. But that's basically my only reason for leaning towards this approach so if that doesn't feel like a deal breaker than I think we could go either way with this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment