Welcome to our blog!

Organizing React Components for Better Code

Image designed from Canva Pro

Organizing your components in their own files is a good practice.

Your code becomes maintainable and well organized.

As a reminder from my last post, we first need to import React from the React package in every file we use for React.

Yes, besties. You read that right. Every. File. 😝 Yikes, I know. lol

Alright, so here are our first three steps:

  1. Import React from the React package
  2. Create a functional component
  3. Export our component. In this example, we use the default export Greeting (depends on how you named your file)

Greeting.jsx

import React from "react";
const Greeting = () => {
return <h1>Hello, there!</h1>;
};

export default Greeting;

So now, let’s move onto our index.jsx file!

  1. Import your component
  2. Render the component in the root element

index.jsx

import React from "react";
import { createRoot } from "react-dom/client";
import Greeting from "./Greeting";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

And just for the purposes of this post, we are going to export our other component called Message.

Message.jsx

import React from "react";
const Message = () => {
return <h1>Welcome to the Jungle!</h1>
};
export default Message;

Alright, now that we got that review down, did you know that you can create as many components as you want?

Creating different file components can keep your code organized and maintainable. 

But of course, do it strategically or else what is even the point of doing this? You’re also going to thank me later once we start combining TypeScript with React.

Every component can only return one element. Thus, if you want to include a new one, you must wrap the existing JSX in an element. To do this, we need a parent element around the JSX that the component would return.

Geez CyCy, what gibberish are you spouting now? Can we please go back to reading your fictional gibberish? LOL

Don’t worry, here’s the codes so you can see what I’m talking about. 

index.html

<html>
<head>
<script type="module" src="./index.js"></script>
</head>
<body>
<div id="root">loading</div>
</body>
</html>

index.jsx

import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(<App />);

App.jsx

import React from "react";
import Greeting from "./Greeting";

const App = () => {
return (

<div>

<h1>Welcome to my React app!</h1>

</div>

);
};

export default App;

Greeting.jsx

import React from "react";

const Greeting = () => {
return <h1>Hello, there!</h1>;
};

export default Greeting;

Alright, so that’s pretty simple right? But what if, hear me out, you want to return more than one line of JSX? After all, coding is about having a billion lines (I’m kidding…not really).

Then we wrap the returned JSX inside the parentheses. You are going to add a <div> element around the JSX that the component returns.

By doing this, you can add as many elements as you want inside!

Keep in mind that a component is like a building block―just like an element. Therefore, you can add a component as often as you want.

App.jsx

import React from "react";
import Greeting from "./Greeting";

const App = () => {
return
(

<div>
<h1>Welcome to my React app!</h1>
<p>I'm happy that you are here.</p>
<Greeting/>
</div>

);
};

export default App;

Did you also know that you can put multiple components into one file?

You can directly use a component that was defined in the same file. Seems logical enough, right?

App.jsx

import React from "react";

const App = () => {
return <div></div>;
};

export default App;

Components.jsx

import React from "react";

const Article = () => {
return (
<div>
<h2>Bank Heist</h2>
<p>A local bank was hit by unidentified suspects...no thanks to SpiderMan!</p>
</div>
);
};

const App = () => {
return (
<div>
<h1>Daily Bugle</h1>

<Article/>

</div>
);
};

export default App;

And on that same logic, you can also export multiple classes using named exports instead of a default export.

Excusez-moi, CyCy. You don’t make any sense.

Well, here’s the code so you know what I mean:

Components.jsx

import React from "react";

export const Article = () => {
return (
<div>
<h2>Bank Heist!</h2>
<p>A local bank was hit by unidentified suspects...no thanks to SpiderMan!</p>
</div>
);
};

export const Header = () => {
return <h1>Daily Bugle</h1>;
};

You simply put the export keyword in front of every component you want to export. In this example, we have the Article and the Header.

Now, to import multiple named exports from the same file, you just list each item in curly braces. You guessed it right! It’s the Article and the Header.

App.jsx

import React from "react";
import {Article, Header} from "./Components";

const App = () => {
return (
<div>
<Header />
<Article />
</div>
);
};

export default App;

But let’s say you only want to import the Article and not the Header (or vice versa), then just simply omit the component you don’t want.

Simple, huh?

App.jsx

import React from "react";
import {Header} from "./Components";

const App = () => {
return (
<div>
<Header />
<p>Spiderman needs to get a grip! Vigilante hero? Oh, please. He's a criminal dressed in a spider suit!</p>
<p>Spiderman is just a cosplaying pervert!</p>
</div>
);
};

export default App;

Alright, quick review before I move on:

  1. How would we export both, like in this example, Article and Header, by using named exports? We do it by: export before each component
  2. Named exports allow multiple exports from a single file
  3. The named exports are placed inside the {} brackets.

Last stretch, I promise!

Now, we can also choose to make one of the exports the default export when we export multiple components.

Components.jsx

import React from "react";

export
const Spiderman= () => {
return (
<div>
<h2>Spiderman's real identity revealed?!</h2>
<p>We got breaking news that our cosplaying perverted vigilante is no other than Peter Parker!</p>
<p>A broke grad student that works here at <strong>Daily Bugle</strong> part-time!</p>
<p>Oh sh**. He works here?!</p>
</div>
);
};

const Header = () => {
return <h1>Daily Bugle</h1>;
};

export default Header;

Then we import that default export via the import statement and define the path to the file.

App.jsx

import React from "react";
import Header from "./Components";


const App = () => {
return (
<div>
<Header />
</div>
);
};

export default App;

Now, to import a named export alongside a default exported component, we list them inside the curly braces and add them to the same import statement.

App.jsx

import React from "react";
import Header, {Spiderman} from "./Components";

const App = () => {
return (
<div>
<Header />
<Spiderman />
</div>
);
};

export default App;

We can also ignore the default export and import only the named export.

App.jsx

import React from "react";
import {Spiderman} from "./Components";


const App = () => {
return (
<div>
<h1>Ban Spiderman from the streets of New York!</h1>
<Spiderman />
</div>
);
};

export default App;
  1. import React from “react” is the statement which imports React into our app
  2. In your index.html, make sure you create the right tag in order for your React App to work. For example, if you named you <div> as “panel,” then in your index.jsx, it’s const rootelement = document.getElementbyId(“panel”);
  3. We use embedded expressions to insert JSX element into other elements
  4. The building block of a React app is called Components
  5. Each React component file should begin with an import statement for React
  6. The purpose of the export default statement is to make the component accessible in other files
  7. The correct tag name for a component in React is <ComponentName />
  8. The rule for rendering React components is that the components must start with a capital letter
  9. You need a parent element if you want to return multiple elements
  10. Since you can only return one element at a time, then you must use return() if you want to return more than one

index.html

<!doctype html>
<html>
<head>
<link rel="stylesheet" href="./index.css" />
<script type="module" src="./index.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>

index.jsx

import React from "react";
import { createRoot } from "react-dom/client";

const Profile = () => {
const name = <strong>Peter Parker</strong>;

const dob = <i>Aug 10, 2001</i>;

return (
<div>
<h1>Profile</h1>
<ul>
<li>Name: {name}</li>
<li>Date born: {dob}</li>
</ul>
<img src= {url} alt="Peter Parker" />
</div>
);
};

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(<Profile />);


  • Implementing Dark Mode in React

    We have previously talked about useState before. A great way to create CSS classes on the fly is to use state variable! Here is an example of how to create Dark Mode in React by using string interpolation to construct the individual classes based on the state variable mode. index.html index.jsx App.jsx App.css So, if…

  • Understanding React’s useState Hook

    Buttons To use buttons, you can add the onClick event handler to handle clicks on the button. React also follows the camelCase unlike HTML/JavaScript; and to run the JavaScript, you add an embedded expression. App.jsx You can also run JavaScript directly inside the embedded expression. However, it is executed without clicking the button because the function is…

  • Understanding Props in React: A Comprehensive Guide

    This content explains the concept of props in React, which allow data to be passed to components, making them dynamic. It covers how to access props as objects, pass multiple properties, and handle different data types. The importance of correctly rendering non-string values and using props in JSX is emphasized.

  • The Power of JSX: Combining HTML and JavaScript

    JSX is a syntax extension for JavaScript that resembles HTML, used primarily in React to create components. It allows developers to write HTML-like code within JavaScript, enhancing readability and enabling dynamic web applications. With JSX, one can embed JavaScript expressions, making the integration of logic and UI layout seamless.

  • Organizing React Components for Better Code

    The content discusses best practices for organizing React components in separate files for maintainability. It details the process of importing React, creating functional components, and exporting them. Additionally, it covers returning multiple elements and using named vs. default exports, emphasizing strategic organization for better code management.

  • Step-by-Step Guide to Rendering React Components

    The content provides a step-by-step guide on rendering components in React. It emphasizes creating and linking HTML and JavaScript files, setting up the main component, and utilizing the createRoot function to manage rendering. The author injects humor while guiding readers through the essential concepts of React component rendering.

  • Introduction to React: Understanding the Basics

    React is a JavaScript library for creating single-page web applications that dynamically update without page reloads. It organizes code into reusable components, akin to functions returning HTML-like JSX. This enhances development efficiency, as components can be reused, resembling custom HTML tags. Overall, React simplifies coding while improving functionality.

  • HTML Structure Explained: A Beginner’s Guide

    The content discusses HTML, the foundational markup language for web development. It highlights its structure, including elements like tags and attributes. The post humorously reflects on the author’s learning journey while encouraging newbies by simplifying concepts like nesting elements and the importance of HTML in web design. It concludes with code examples.

  • Why Use Pure Functions in React Components?

    Pure functions in JavaScript are self-contained and produce consistent results without affecting external variables or objects. They enhance clarity and maintainability in code, minimizing bugs. Unlike impure components that modify existing variables, pure components receive data as props. Understanding component relationships, like the React render tree and module dependency tree, further optimizes performance and structure.

  • React Components Explained: A Guide for Developers

    This post analyzes React components, highlighting their crucial role in creating dynamic user interfaces. It details the types of components, including functional and class components, and explains props and state. Additionally, it covers lifecycle methods and emphasizes the importance of reusability and composition in building complex applications effectively.



Discover more from Steal My Notes

Subscribe to get the latest posts sent to your email.

Posted by

in

Discover more from Steal My Notes

Subscribe now to keep reading and get access to the full archive.

Continue reading