0

Being new to React am stuck with something that should seemingly be pretty straightforward. Not sure what am doing wrong.

I have a component BasicReactComponent.js like this:

import React from 'react';

const BasicReactComp = () => {
  console.log('hi');
  return (
    <div>
      I was loaded from basic react comp.
    </div>
  );
};

export default BasicReactComp;

Am trying to call it in my main file like below:

import React from 'react';
import ReactDOM from 'react-dom';
const BasicReactComp = require('./BasicReactComp');

ReactDOM.render(
 <BasicReactComp />,
 document.getElementById('foo')
);

I keep getting the below error

**Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
    Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.**
Mr. ProxY
  • 17
  • 1
  • 4
prgrmr
  • 842
  • 3
  • 14
  • 30

1 Answers1

2

When translating between ES6 modules and CommonJS modules, default exports are exported as a default property. Hence you have to access .default of the value you require:

const BasicReactComp = require('./BasicReactComp').default;

Or use the import syntax:

import BasicReactComp from './BasicReactComp';
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • #FacePalm.... Thank you so much... That fixed it :) – prgrmr Jun 05 '17 at 04:56
  • @felix-king, do you happen to know if there is a way I could do something like this... $('#foo').append(ReactDOM.render( , document.createElement('div') )); For some reason it isnt working... The thing is I would want the component to be rendered inside a div which is appended to another element – prgrmr Jun 05 '17 at 05:15
  • Nevermind figured it :) – prgrmr Jun 05 '17 at 05:21