skip to Main Content

Hi I am new to React and learning about it. While I was learning about Named and Default Exports I ran into a issue. I am not sure how to explain my doubt in words here is my code.

namedExport.js

const name = "xyz";
const age = 20;

const myFunc = () => {
    const name = "abc";
    const age = 21;
    return (<>
    <h2>{name} is {age} years old.</h2>
    </>);
}

export {name, age}
export {myFunc}

defaultExport.js

const myFunction = () => {
    const name = "ijk";
    const age = 22;
    return (<>
    <h3>{name} is {age} years old.</h3>
    </>);
}

export default myFunction

App.js

import { name, age, myFunc } from "./namedExportTest";
import myFn from "./defaultExportTest";

function App() {
  return (
    <div className="App">
      <h1>Hi Everyone</h1>
    </div>
  );
}

function Exports() {
  return (
    <>
      <div className="exportNamed">
        <h1>My name is {name}, I am {age}.</h1>
      </div>
      <myFunc />
      <myFn />
    </>
  );
}

export {Exports};
export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import {Exports} from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
    <Exports />
  </React.StrictMode>
);

I am not getting the Expected Output.
My Expected Output:

Hi Everyone //in h1 tag
My name is xyz, I am 20. //in h1 tag
abc is 21 years old. //in h2 tag
ijk is 22 years old. //in h3 tag

But the output I got is:

Hi Everyone //in h1 tag
My name is xyz, I am 20. //in h1 tag

I am not sure what is the mistake I did. If anyone know what mistake I did, please post it with the Code Example to get my Expected Output.

Thanks!

2

Answers


  1. If you are using default exports and named exports in a same file, you have to import them in a single line in the index.js file.

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

    How to import both default and named from an ES6 module

    Login or Signup to reply.
  2. The issue is that React component names must start with a capital letter, so myFunction should be MyFunction, and myFunc should be MyFunc. I get your desired output when fixing this capitalization issue in both the component files and the file importing the components.

    By the way, you are importing from ./namedExportTest and from ./defaultExportTest; however your files are called namedExport.js and defaultExport.js.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search