Skip to content

Instantly share code, notes, and snippets.

@kilmc
Created August 21, 2020 14:21
Show Gist options
  • Select an option

  • Save kilmc/797ceb72fec6958227644450ac830992 to your computer and use it in GitHub Desktop.

Select an option

Save kilmc/797ceb72fec6958227644450ac830992 to your computer and use it in GitHub Desktop.
Adjustable Heading Levels
import React, { createContext, useContext } from 'react';
const HeadingLevelContext = createContext<number>(0);
type HTMLTag = keyof JSX.IntrinsicElements;
interface HeadingProps {
children: React.ReactNode;
level: 1 | 2 | 3 | 4 | 5 | 6;
}
function Heading(props: HeadingProps) {
const { level, ...rest } = props;
const headingLevelOffset = useContext(HeadingLevelContext) + props.level;
const headingLevel = headingLevelOffset > 5 ? 6 : headingLevelOffset;
const Tag = `h${headingLevel}` as HTMLTag;
return <Tag {...rest} />;
}
export function Component() {
return (
<HeadingLevelContext.Provider value={0}>
<div>
<Heading level={1}>A top level heading</Heading>
<p>A bunch of content</p>
<Heading level={2}>A sub-level heading for a list</Heading>
<ul>
<li>Fruits</li>
<li>Vegetables</li>
<li>Spices</li>
</ul>
</div>
</HeadingLevelContext.Provider>
);
}
<!-- When HeadingLevelContext.Provider value={0} -->
<div>
<h1>A top level heading</h1>
<p>A bunch of content</p>
<h2>A sub-level heading for a list</h2>
<ul>
<li>Fruits</li>
<li>Vegetables</li>
<li>Spices</li>
</ul>
</div>
<!-- When HeadingLevelContext.Provider value={2} -->
<div>
<h3>A top level heading</h3>
<p>A bunch of content</p>
<h4>A sub-level heading for a list</h4>
<ul>
<li>Fruits</li>
<li>Vegetables</li>
<li>Spices</li>
</ul>
</div>
<!-- When HeadingLevelContext.Provider value={5} -->
<div>
<h6>A top level heading</h6>
<p>A bunch of content</p>
<h6>A sub-level heading for a list</h6>
<ul>
<li>Fruits</li>
<li>Vegetables</li>
<li>Spices</li>
</ul>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment