Search code examples
reactjsreflectionrenderbabeljstagname

reflection to pass tagName as string props to be rendered


class Button  extends React.Component{
    renderAnchor(){
      return <a onClick={this.props.onClick}>{this.props.children}</a>
    }
    renderButton(){
       return <button onClick={this.props.onClick}>{this.props.children}</button> 
    }
    render(){
         return (this.tagName==='a')?this.renderAnchor():this.renderButton();
    }

}

I have the above react-component , i want to avoid code redundancy, so , i decide to remove all render methods except the last (render) by replacing the tagname by this.props.tagName

     render(){
         return <{this.props.tagName} onClick={this.props.onClick}>{this.props.children}</{this.props.tagName}>
    }

However, it raises an error of syntax .

How can use reflection of tagname in react / ES7/ Babel ?


Solution

  • You can assign the tag name to a variable and use that variable as the HTML tag.

    For example:

    render(){
        const CustomTag = this.props.tagName //assign it to the variable
    
        return <CustomTag
          onClick={this.props.onClick}>
              {this.props.children}
          </CustomTag>
    

    Demo: https://jsfiddle.net/88honb0z/