Understanding when and how to use import and export in React
Tags: webdev, frontend, react, javascript
Published: 2023-09-02 21:10:35

React operates as a component-based framework, allowing you to reuse components throughout your codebase. Component reusability involves reusing components wherever necessary, made possible by using the import and export statements.

###Prerequisites 

Before you proceed with this article, It's important you're familiar with:

- React
- JavaScript

###Understanding When to Import and Export

It's important to understand that when you talk about importing a component, there must first be a component to export. So, let's begin by looking at what the export does.


**Export**: Exporting is about making your component, function, or variable usable in other files.

**In React, these shared parts are usually components, functions, or information that are helpful. When you export something, you say, "Hey, other parts of the code or external files can use this, too!" This is useful for keeping your code organized and making it easy to use repeatedly.**

**For example, if you've made a special button in your React project, like a `Button` you can export it. Then, other parts of your project can use the same button without making a new one. It's like sharing your cool toy so everyone can play with it.**

```
function Button(props) {

    const {value, id, className } = props;
    return (
      <button
          id={id}
          className={`${className}`}
      >
          {value}
      </button>
    )
}

export default Button
```

In this part of the code, you create a custom React component called `Button`. This component takes in some properties (props) you can customize when using this component in your app.

You're extracting values from the props object inside the component using destructuring. These values are value, id, and className.

The component returns a button element with the specified properties. This Button component is designed to render a button with the provided text (value), id, and className.

Finally, you're using `export default` to export the Button component. This means that other parts of your app can import and use this special Button component.

**Import**: Importing, on the other hand, is about making a component, function, or variable accessible to be used in a specific file.

Importing and exporting go hand in hand. Once you've shared something by exporting it, you can grab it and use it in a different part of your code by importing it. It's like borrowing a cool tool from a friend.

When you import, you prevent the need to copy and paste the same thing repeatedly. That way, your code stays neat, and you don't have to worry about making mistakes.

Another bonus of importing is that it helps you keep your codebase organized. Instead of having one huge pile of code, you can split it into smaller pieces. Each piece can import just what it needs, making your work much cleaner and simpler.

So, importing isn't just about bringing things in; it's about keeping your program clean and avoiding mistakes.

Now, let's move on to the next part of the code:

```
import { ComponentA, ComponentB, ComponentC } from './Componentfiles'
import Button from './Button.'

function ComponentD() {

  return (
      <div>
        <ComponentA />
        <ComponentB />
        <ComponentC />
      
        <Button
          value= "Learn More"
          id= "btnLearn"
          className="btn btn-primary" //blue button
        />
    </div>
  )
}

export default ComponentD
```

Import the custom Button component that you defined earlier inside `ComponentD`. 

Lastly, you're using the Button component you imported. You're passing specific properties (like value, id, and className) to customize how the button should look. These properties can differ where you're using the special Button component.

For instance, you want to use the Button component in `ComponentA` with a different text, looks, and id.

```
export function ComponentA() {
  return (
    <div>
      ComponentA
      <Button
        value= "Click A"
        id= "btnClick"
        className="btn btn-warning" //yellow button
      />
    </div>
  )
}
```
And here is the final result.


![Button component final result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zue2icvlypwuiskd605v.png)

###How to Export and Import Components

There are two methods for exporting a component:

- Default export
- Named export

Each approach has its distinct way of importing, and you can decide to use either the `default export` statement in a file or a combination of both default and `named export` statements within a file.

**Default export:** The default export statement is automatically added to your `App.js` file when you create a React project, usually found at the end of the code.
The `default export` can only be used once within a file.

![default export component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a4d6ywuarpzkswp4iqrf.png)


```
//App.js
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

function App() {
  const [count, setCount] = useState(0)

  return (
    <>
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo"
          />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" 
          alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <button onClick={() => setCount((count) => count + 
        1)}>
          count is {count}
        </button>
        <p>
          Edit <code>src/App.jsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </>
  )
}

export default App //default export statement
```

Your `App.js` file might have a different appearance than the example shown above due to my use of the Vite tool for setting up the React project.

For more details, refer to my previous article: [Create React App vs Vite: Which One Should You Choose for Your Next React Project?](https://dev.to/esedev/create-react-app-vs-vite-which-one-should-you-choose-for-your-next-react-project-5268)

Create a new component and add the default export statement followed by your component name.

**Like this**

```
//ComponentA
function ComponentA() {
  return (
    <div>ComponentA</div>
  )
}

export default ComponentA
```

**or this**

```
//ComponentA
import React from 'react'

export default function ComponentA() {
  return (
    <div>ComponentA</div>
  )
}
```

Both methods will give the same outcome. The only difference lies in how they're implemented. In the first approach, after creating the function, the default export statement `export default ComponentA` is placed at the end of the code.

The `export default` is positioned on the same line as the function in the second approach.

**Importing a component with a default export**

Now, let's get your components talking to each other. To import a component that's been default exported, use the import keyword followed by your chosen name and the file's export path.

Create a new component named ComponentB and proceed to import `ComponentA` in `ComponentB`.

**Like this**

```
//ComponentB
import React from 'react'
import ComponentA from './ComponentA'

function ComponentB() {
  return (
    <div>
      <ComponentA/>
    </div>
  )
}

export default ComponentB
```

**Note:** When dealing with a default export statement, you can choose any name after the `import` keyword, while the path should point to the original file, which in this case is `ComponentA.js`. 

This practice applies only when importing a default export statement component.

**Like this**

```
//ComponentB
import React from 'react'
import FirstComponent from './ComponentA'

function ComponentB() {
  return (
    <div>
      <FirstComponent/>
    </div>
  )
}

export default ComponentB
```

**Named export:** The named export statement comprises the export keyword, the function keyword, and the component's name. The named export can be used in a file to export multiple components.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7bg796nboz3ny4sne2l8.png)

**Like this**

Single component

```
import React from 'react'

export function ComponentA() {
  return (
    <div>ComponentA</div>
  )
}
```

Multiple named export statement components in a file named `Componentfiles.js`


```
import React from 'react'

//ComponentA
export function ComponentA() {
  return (
    <div>ComponentA</div>
  )
}

//ComponentB
export function ComponentB() {
  return (
    <div>ComponentB</div>
  )
}

//ComponentC
export function ComponentC() {
  return (
    <div>ComponentC</div>
  )
}

```

**Importing a component with a named export**

To import a named component, utilize the import keyword, enclose the component name within curly braces `{}`, and specify the path to the exported file.

When importing multiple components within a file, encase all the component names within the curly braces {}. These component names within the curly braces must precisely match the names of the exported components.

**Like this**

```
import React from 'react'
import {ComponentA, ComponentB, ComponentC} from './Componentfiles'

function ComponentD() {
  return (
      <div>
          <ComponentA />
          <ComponentB />
          <ComponentC/>
    </div>
  )
}

export default ComponentD
```


###Summary

You learned about understanding import and export statements in React, and we also looked at the following:

- When and How to import and export a component
- Two(2) ways to export(default export and named export) a component and
- Importing a component with a default export and named export statement.

Well done on finishing this article! If you have questions, I'm here to help. Connect with me on social media **@EstherItolima** or email [itolimaesther@gmail.com](itolimaesther@gmail.com) for more support. Your interest matters, and I'm excited to assist you!