Embet Isit
Embet Isit

Reputation: 321

How does one import a child component in react?

The component which is external includes and external file

  class NavigationBarContainer extends React.PureComponent {
 render = () => <NavigationBar extraBanner={<Banner 
   />} {...this.props} />

}

in my App

   import NavigationBar from '../components/NavigationBar'

    <NavigationBar
      extraBanner />

doesn't seem to work

  import NavigationBarContainer from '../components/NavigationBar'
     <NavigationBarContainer {...this.props}>

doesnt seem to work either getting error below

**Invalid prop extraBanner of type boolean supplied to NavigationBar, expected a single ReactElement.**

Upvotes: 2

Views: 4065

Answers (1)

grammar
grammar

Reputation: 871

Two possible things that are wrong here.

1) NavigationBarContainer is not being exported, thus you cannot import it.

You can fix this by making sure to export the class one of two ways -- either change the class declaration to include the export keyword

export default class NavigationBarContainer extends React.PureComponent

or add a line to the bottom of that file

export default NavigationBarContainer;

2) You are trying to import a component called NavigationBarContainer from a file called NavigationBar. If that file is called NavigationBarContainer then this will not work. Make sure that your file names are correct.


A quick summary of export vs export default and importing

export default

The default export can be given any name when imported, eg.

// components/MyComponent.js
export default class MyComponent extends React.Component {...}

// AnotherFile.js
import MyComponent from 'components/MyComponent'; // works
import WhateverName from 'components/MyComponent'; // also works

export

When you don't use the default keyword, then you're making a named export. These have to be imported directly by name, using this syntax:

// components/SmallComponents.js
export class SmallComponent1 extends React.Component {...}
export class SmallComponent2 extends React.Component {...}

// AnotherFile.js
import {SmallComponent1, SmallComponent2} from 'components/SmallComponents'; // works
import SmallComponent1 from 'components/SmallComponents' // does not work
import {WhateverName} from 'components/SmallComponents' // does not work

Hope this helps!

Upvotes: 2

Related Questions