I am fairly new to React & JSX however I was under the impression that you can save JSX as pretty much anything (var,const, let...).
However when I save it as a const and try to render it like so:
import React from 'react';
import ReactDOM from 'react-dom';
const Test = <div> hi </div>;
ReactDOM.render((
<div>
<Test />
</div>
), document.getElementById('root'));
I get the error message:
React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
And when I replace the test const with the following:
const Test = () => { return( <div> hi </div> ) };
It renders no problem. Why can't I use the first version?
You can use the first one, but in that case it will be not a React component, it's just a variable referencing the result of creating the div
, so render it like this:
const Test = <div> hi </div>;
ReactDOM.render((
<div>
{Test} //here
</div>
), document.getElementById('root'));
Or, to make it a Stateless Functional Component (SFC), write it as a function returning that div
:
const Test = () => { return( <div> hi </div> ) };
Then you can use it as <Test />
.
Check the DOC for more details about JSX.
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