Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't JSX saved as a const rendering

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?

like image 258
Atomicts Avatar asked Aug 11 '17 09:08

Atomicts


1 Answers

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.

like image 96
Mayank Shukla Avatar answered Sep 18 '22 01:09

Mayank Shukla