Just wondering if there is anyway to set heading levels by passing props down to the base component.
Example:
Base Component
class Heading extends Component {
 render() {
  return (
    <h{this.props.headinglevel} className={this.props.titleStyle}>
        {this.props.title}
    </h{this.props.headinglevel}>
  );
 }
}
export default Heading;
Parent Component (Passing Props)
class HomeHeader extends Component {
 render() {
  return (
      <Heading headinglevel="1" titleStyle="big-header" title="Hello World" />
  )
 }
}
export default HomeHeader;
When I try this I get a syntax error.
Yup! The way to make your tag a variable is as such:
render() {
    const Tag = 'h1';
    return <Tag>{/* some code here */}</Tag>;
}
Notice that Tag is capitalized. It is required you capitalize a tag variable so React understands it's not just a normal HTML element.
So in your case, you could do something like:
render() {
  const Tag = 'h' + this.props.headinglevel; // make sure this has a default value of "1" or w/e
  return (
    <Tag className={this.props.titleStyle}>
        {this.props.title}
    <Tag>
  );
}
(If you're being safe, you may want to add some check so this.props.headinglevel can only be 1-6.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With