Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JSX file giving error "Cannot read property 'createElement' of undefined"

I have a file test_stuff.js that I am running with npm test

It pretty much looks like this:

import { assert } from 'assert';
import { MyProvider } from '../src/index';
import { React } from 'react';

const myProvider = (
  <MyProvider>
  </MyProvider>
);

describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});

Unfortunately, I get the error

/Users/me/projects/myproj/test/test_stuff.js:11
var myProvider = _react.React.createElement(_index.MyProvider, null);
                             ^

TypeError: Cannot read property 'createElement' of undefined
    at Object.<anonymous> (/Users/me/projects/myproj/test/test_stuff.js:7:7)

What does that mean? I am importing React from 'react' successfully, so why would React be undefined? It is _react.React, whatever that means...

like image 357
Some Guy Avatar asked Sep 10 '16 05:09

Some Guy


3 Answers

To import React do import React from 'react' You add brackets when the thing you are importing is not the default export in that module or file. In case of react, it's the default export.

This might apply to your other imports depending on how you defined them.

like image 106
Kafo Avatar answered Oct 19 '22 07:10

Kafo


import React, { Component } from 'react'

This worked for me. I'm not sure why it fixed my version of this issue, though. So if you are someone who stumbled upon this problem and you use create-react-app as your starting boilerplate, this way of importing React will do the trick. (as of Oct '18, lol)

like image 51
TJ Allen Avatar answered Oct 19 '22 08:10

TJ Allen


For those who are working ReactJS with TypeScript.

import * as React from 'react';
like image 34
Khuong Avatar answered Oct 19 '22 08:10

Khuong