Default Or Named Export

Default Or Named Export

  • ES6 provides us to import a module and use it in other file.

  • ES6 provides two ways to export a module form a file:

    1. named export

    2. default export

Default Export: (export default)

  • One can have only one default export per file.

  • when we import we have to specify a name.

      function App() {
        return (
          <div>
            <h1>hii,hello</h1>
          </div>
        )
      }
    
      export default App;  //default export
    

    and call with any name in import file like:-

    import New from './App'

NAMED EXPORT: (export)

  • With named export, one can have multiple named export per file

  • Then import the specific exports they want surrounded in curly braces.

  • The name of import module has to be the same as the name of the exported module.

      function App() {
        return (
          <div>
            <h1>hii,hello</h1>
          </div>
        )
      }
    
      function App2() {
        return (
          <div>
            <h1>hii,hello</h1>
          </div>
        )
      }
    
      export {App, App2};
    

    and import with same name like:-

    import {App, App2} from './App';

Both export together

We can use default or named export with together lile:-

function App() {
  return (
    <div>
      <h1>hii,hello</h1>
    </div>
  )
}

function App2() {
  return (
    <div>
      <h1>hii,hello</h1>
    </div>
  )
}

export default App;
export {App2};

and we can call in one line or import both exports like:-

import App,{App2} from './App';

Also write like:

  1. EXPORT with CLASS Component:-
//default export
import React, { Component } from 'react'
export default class User extends Component {
   render() {
     return (
       <div>

       </div>
     )
   }
 }

//named export
import React, { Component } from 'react'
export class User extends Component {
   render() {
     return (
       <div>

       </div>
     )
   }
 }
  1. EXPORT with FUNCTION COMPONENT:-

     //DEFAULT EXPORT
     export default function User2(){
          return(
              <>
              <h4>function component</h4>
              </>
          );
      }
    
     //NAMED EXPORT
     export function User2(){
          return(
              <>
              <h4>function component</h4>
              </>
          );
      }
    

HAPPY LEARNING