mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Dynamically Create HTML Elements as a react til
This commit is contained in:
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
||||
For a steady stream of TILs from a variety of rocketeers, checkout
|
||||
[til.hashrocket.com](https://til.hashrocket.com/).
|
||||
|
||||
_672 TILs and counting..._
|
||||
_673 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -465,6 +465,7 @@ _672 TILs and counting..._
|
||||
- [Destructure Variables As Props To A Component](react/destructure-variables-as-props-to-a-component.md)
|
||||
- [Dispatch Anywhere With Redux](react/dispatch-anywhere-with-redux.md)
|
||||
- [Dynamically Add Props To A Child Component](react/dynamically-add-props-to-a-child-component.md)
|
||||
- [Dynamically Create HTML Elements](react/dynamically-create-html-elements.md)
|
||||
- [Enforce Specific Values With PropTypes](react/enforce-specific-values-with-proptypes.md)
|
||||
- [Force A Component To Only Have One Child](react/force-a-component-to-only-have-one-child.md)
|
||||
- [Inactive And Active Component Styles With Radium](react/inactive-and-active-component-styles-with-radium.md)
|
||||
|
||||
30
react/dynamically-create-html-elements.md
Normal file
30
react/dynamically-create-html-elements.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# Dynamically Create HTML Elements
|
||||
|
||||
An HTML element can be created with a string that matches a recognized
|
||||
entity.
|
||||
|
||||
```javascript
|
||||
const Paragraph = 'p';
|
||||
return <Paragraph>Some paragraph content</Paragraph>
|
||||
```
|
||||
|
||||
This means we can dynamically create HTML elements such as headers:
|
||||
|
||||
```javascript
|
||||
const H = ({ level, ...props }) => {
|
||||
const Heading = `h${Math.min(level, 6)}`;
|
||||
return <Heading {...props} />;
|
||||
};
|
||||
|
||||
return (
|
||||
<React.Fragment>
|
||||
<H level={1}>Header 1</H>
|
||||
<H level={2}>Header 2</H>
|
||||
<H level={5}>Header 5</H>
|
||||
</React.Fragment>
|
||||
);
|
||||
```
|
||||
|
||||
With some
|
||||
[inspiration](https://medium.com/@Heydon/managing-heading-levels-in-design-systems-18be9a746fa3),
|
||||
I've created a [live example here](https://codesandbox.io/s/3v202wmmy1).
|
||||
Reference in New Issue
Block a user