Why does my React Component Export not work?

40,272

Solution 1

Because your export is default you don't need braces around your import component name:

import Hello from './hello';

Here's a verbose technical article from Axel Rauschmayer on the final ES6 modules syntax that you might find useful.

And here's a slightly less techy post about the same topic.

Solution 2

when you import the default class you use

import ClassName from 'something';

and when you import other classes you use

import {ClassName} from 'something';

an example:

in hello.js file

import React from 'react';

class Hello extends React.Component{
   render(){
       return (
           <h1>Hello, world!</h1>
       )
    }
}

class Other extends React.Component{
   render(){
       return (
           <h1>Hello, world!</h1>
       )
    }
}
export default Hello;
export Other;

in other file

import Hello, {Other} from './hello';

tip: you could also import the default class with other name

import Component, {Other} from './hello';
Share:
40,272
gerdtf
Author by

gerdtf

Updated on December 04, 2020

Comments

  • gerdtf
    gerdtf over 3 years

    I was just getting into react and trying it out for myself. After hours of configuring webpack just to get a hello world on my screen I thought I could get going now but after trying to render another component from a file the next problem.

    My main file is app.js, which renders everything:

    import React from 'react';
    import ReactDOM from 'react-dom';
    import {Hello} from './hello';
    
    ReactDOM.render(
       <Hello/>,
       document.getElementById('app')
    );
    

    The Hello component comes from my hello.js in the same folder:

    import React from 'react';
    
    class Hello extends React.Component{
       render(){
           return (
               <h1>Hello, world!</h1>
           )
        }
    }
    
    export default Hello;
    

    It was rendering fine when I was doing everything just in app.js without the import/export. It also compiles fine. But there are a lot of errors now in the console. So what am I missing?

    Thanks

    Gerd

  • gerdtf
    gerdtf over 6 years
    thanks a lot for not only getting a rookie up and running but also making him understand what the actual difference is.
  • Jenna Rajani
    Jenna Rajani over 6 years
    This is an excellent example however the Other component would also need it's own export statement.