Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Heading Level With Props React

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.

like image 391
Ash._ Avatar asked Nov 05 '17 17:11

Ash._


Video Answer


1 Answers

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.)

like image 191
SamVK Avatar answered Sep 28 '22 16:09

SamVK