DEV Community

Desiree Ann Zarco
Desiree Ann Zarco

Posted on

How to organize your code using Import and Export in React

As a developer, it is important to keep your code clean and well organized, especially when you're working with long blocks of code. Learning import and export was a little challenging for me when I first started to learn React, but it is actually pretty straightforward. We basically give "access" to the codes within files that will be using it. Sounds confusing, but let's go with this simple example:

NavBar.js file

import React from "react";

function NavBar() {
  return (
    <nav>
      <a href="#home">I'm a link!</a>
    </nav>
  );
}

export default NavBar

Enter fullscreen mode Exit fullscreen mode

When you want to use your code in another component, you share it by writing export default at the bottom of your code.

App.js file

import React from "react";
import NavBar from './NavBar'

function App() {
  return (
    <div>
      <NavBar />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

When you need to use a component, you need to import it at the top of the file, like the example above.
import NavBar from './NavBar'

If you noticed at the top of the file, it usually starts with import React from "React"; and that is because in React, we are writing in JSX. JSX is JavaScript XML. JSX allows us to write HTML and React Components in React.
Let's import another component to our App.js file.

About.js file 

import React from "react";

function About() {
  return (
    <div id="about">
      <h2>About Me</h2>
    </div>
  );
}

export default About
Enter fullscreen mode Exit fullscreen mode
App.js file

import React from "react";
import NavBar from './NavBar';
import About from './About';

function App() {
  return (
    <div>
      <NavBar />
      <About />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

If you want to practice, try adding another component to the App.js file. Make a new file, name it Home.js, and inside the Home.js file, you can write a basic function, then you would export the name of your file that you want to share and use in your other files
export default Home;

Move to the App.js file and import that file at the top, like so:

App.js file

import React from "react";
import NavBar from './NavBar';
import About from './About';
import Home from "./Home';

function App() {
  return (
    <div>
      <NavBar />
      <About />
      <Home />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Don't forget to add the component itself, inside your function.

Test this out on your own and see that it works! This is just the basics on how to import and export in between your files and work with usable components.

Top comments (0)