Set header level with props

Just wondering if there is a way to set header levels by passing details 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 (pass passes)

 class HomeHeader extends Component { render() { return ( <Heading headinglevel="1" titleStyle="big-header" title="Hello World" /> ) } } export default HomeHeader; 

When I try to do this, I get a syntax error.

+5
source share
1 answer

Yes! A way to make your variable tag like this:

 render() { const Tag = 'h1'; return <Tag>{/* some code here */}</Tag>; } 

Note that Tag has uppercase letters. You need to use the tag variable, so React understands it not only as a regular HTML element.

So, in your case, you can 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 are safe, you can add some verification, so this.props.headinglevel can only be 1-6.)

+5
source

Source: https://habr.com/ru/post/1273133/


All Articles