Published on Dec 4, 2023 10:48

Importing and Exporting Components

Export Default vs. Named Exports:

Export Default:

When using export default, you are exporting a single default entity (usually a component, function, or class) from a file. This is often used for the main export of a file.

// ButtonComponent.js
import React from 'react';

// Button functional component
const Button = () => {
  return <button>Click me</button>;
};

// Exporting Button as the default export
export default Button;

Now, in another file, you can import it without using curly braces:

// FormComponent.js
import React from 'react';
import Button from './ButtonComponent';

// Form functional component that uses the Button component
const Form = () => {
  return (
    <form>
      <h2>Sample Form</h2>
      {/* Using Button directly without curly braces */}
      <Button />
    </form>
  );
};

export default Form;

Named Exports:

With named exports, you can export multiple entities from a file. These entities must be imported using curly braces {} and the exact name of the export.

// InputComponent.js
import React from 'react';

// Input functional component
export const Input = () => {
  return <input type="text" />;
};

// Exporting Input as a named export
export const someOtherExport = "This is another export";

Now, in another file, you import the named exports using curly braces:

// FormComponent.js
import React from 'react';
import { Input, someOtherExport } from './InputComponent';

// Form functional component that uses the Input component
const Form = () => {
  return (
    <form>
      <h2>Sample Form</h2>
      {/* Using Input directly without default export */}
      <Input />
      {/* Using the named export */}
      <p>{someOtherExport}</p>
    </form>
  );
};

export default Form;

In summary, export default is used when you want to export a single main entity from a file, and it can be imported without using curly braces. Named exports are used when you want to export multiple entities from a file, and they must be imported using curly braces with the exact names.