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
.
As you can see in the first example, JSX allows us to write HTML directly within the JavaScript code.
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)
}
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