Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Create tag dynamically from ES6 template literal with JSX

I need to display a header element in a React render method where the level is dynamically set in the constructor:

class HeaderComponent extends React.Component {

    constructor(props){
        super(props);
        
        this._checkedDepth = Math.min(6, props.depth)
    }

    render(){
        return(<h{ this._checkedDepth }>{ this.props.name }</h{ this._checkedDepth }>)
    }
}

ReactDOM.render(
  <HeaderComponent name="Header 1" depth="2"/>,
  document.getElementById('app')
);
<div id="app"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

This should render <h2>Header 1</h2> with name="Header 1" and depth=2, but I get an error instead:

Uncaught Error: Cannot find module "./HeaderComponent"

What am I overlooking?

I'm using React 15.4.1, babel-preset-es2015 6.9.0, babel-preset-react 6.5.0 and running it in Chrome 55.

like image 254
Marc Avatar asked Jan 13 '17 09:01

Marc


People also ask

Can we use direct JavaScript code in JSX?

As you can see in the first example, JSX allows us to write HTML directly within the JavaScript code.


1 Answers

Each JSX element is just syntactic sugar for calling React.createElement(component, props, ...children). So, anything you can do with JSX can also be done with just plain JavaScript. - https://facebook.github.io/react/docs/react-without-jsx.html

So you can do something like this:

render() {
  return React.createElement(`h${this._checkedDepth}`, this.props)
}
like image 181
T Mitchell Avatar answered Oct 28 '22 11:10

T Mitchell