UNPKG

1.24 kBJSXView Raw
1const React = require('react');
2const PropTypes = require('prop-types');
3
4function generateHeadingId(e) {
5 if (typeof e === 'object') {
6 return generateHeadingId(e.props.children[0]);
7 }
8 return e.toLowerCase().replace(/[^\w]+/g, '-');
9}
10
11function Heading(props) {
12 // Sometimes there might be a case where someone types a header as `#` but doesnt attach any
13 // content to it. We shouldn't try to render it because we'll fail as `props.children` will be
14 // empty!
15 if (typeof props.children === 'undefined') {
16 return null;
17 }
18
19 const id = `section-${generateHeadingId(props.children[0])}`;
20 return React.createElement(props.level, { className: 'header-scroll' }, [
21 <div key={`anchor-${id}`} className="anchor waypoint" id={id} />,
22 ...props.children,
23 // eslint-disable-next-line jsx-a11y/anchor-has-content
24 <a key={`anchor-icon-${id}`} className="fa fa-anchor" href={`#${id}`} />,
25 ]);
26}
27
28function createHeading(level) {
29 // eslint-disable-next-line react/display-name
30 return props => <Heading level={level} {...props} />;
31}
32
33Heading.propTypes = {
34 children: PropTypes.arrayOf(PropTypes.string).isRequired,
35 level: PropTypes.string.isRequired,
36};
37
38module.exports = level => createHeading(level);
39
\No newline at end of file