I have a class which is part of my page layout. It is creating header tag elements (h1
- h5
). Could someone tell me how I could improve it (I know it should be improved, but don't know how)? I have problem with rewriting almost the same code in switch cases. Would rather to create some kind of <h{type}></h{type}>
code, but couldn't.
import React, {Component} from 'react';
import PropTypes from 'prop-types';
export class TypographyHeader extends Component {
createHeader() {
let txt = this.props.text;
let spaceIndex = txt.indexOf(' ');
let p2 = txt.substr(spaceIndex);
txt =
<span className="typography_header__distinctive_el">
{txt.substr(0, spaceIndex)}
</span>;
switch(this.props.headerType) {
case 1:
return <h1 className="typography_header">{txt} {p2}</h1>;
case 2:
return <h2 className="typography_header">{txt} {p2}</h2>;
case 3:
return <h3 className="typography_header">{txt} {p2}</h3>;
case 4:
return <h4 className="typography_header">{txt} {p2}</h4>;
case 5:
return <h5 className="typography_header">{txt} {p2}</h5>;
}
return <h1 className="typography_header">{txt} {p2}</h1>;
}
render() {
return (
<div>
{this.createHeader()}
</div>
);
}
}
TypographyHeader.propTypes = {
headerType: PropTypes.oneOf([1, 2, 3, 4, 5]).isRequired,
text: PropTypes.string.isRequired,
};