Creating Components in React

This series is a starter guide to React.

This is the second article, if you missed the first article you can see it here.

Like all first steps in coding, it's time to create our "Hello World!" example in React.js and create our first component.

Create components

I'll share a guide at the end of this article to set up a new React.js project locally, but for now, let's use an online editor to get you started faster.

You can open the CodeSandbox below in your browser to code along:

I also prefer an online editor for teaching because it's easy to share your code and help you quickly if you are having issues.

What is a Component?

React Components are just JavaScript functions that return some Markup.

They are user interfaces that can be as small as a button or as complex as an entire page.

If we look in our `App. js'file you will see an example of this:

// App.js
export default function App() {
  return (
    <div>
      <h1>Hello World!</h1>
      <p>Getting started with React</p>
    </div>
  );
}

You'll rarely see components as large as pages made up of just markdown.

We usually nest components within other components to start gaining some of the reusable benefits from React.

Nested Components

Let's rewrite the title in our example to be its own component.

At the top of your App.js file add a new function named Title which returns your <h1>Hello World!</h1>.

function Title() {
  return <h1>Hello World!</h1>;
}

Now to we can nest this component inside our App component and replace our title:

function Title() {
  return <h1>Hello World!</h1>;
}

export default function App() {
  return (
    <div>
      <Title />
      <p>Getting started with React</p>
    </div>
  );
}

If you have done everything correctly, you should see nothing new. 🎉

⚠️ Note ⚠️

Notice that <Title /> starts with a capital letter.

That's how you know it's a React component.

React component names must always start with a capital letter, but our HTML must continue to use lowercase.


Import and Export Components

For ease, we currently have both our components (App and Title) in the same file.

As you can imagine, if we had to do this for each component, the file would become an enormous mess!

Let's split our title into it's own file.

Create a new file in your /src directory called Title.js.

Paste in the code for the Title component with a slight alteration. We need to export the component so that we can use it in another file:

// Title.js
export default function Title() {
  return <h1>Hello World!</h1>;
}

Now in our App.js file, import the Title component and everything should still work:

// App.js
// Add the import from the new Title.js file
import Title from "./Title";

export default function App() {
  return (
    <div>
      <Title />
      <p>Getting started with React</p>
    </div>
  );
}

With this knowledge, you can create your own component files, export them and use them in other components.

Homework

To solidify your understanding: Try to convert the <p>Getting started with React</p> into it's own file and component.

Then import that component and replace the existing markup with your new component

The result should be something like this:

import Title from "./Title";
import Description from "./Description"

export default function App() {
  return (
    <div>
      <Title />
      <Description />
    </div>
  );
}

If you can get this working, you are ready to move along!

If not, jump into our Discord; we will help push you along. 🦾

Optional Section - React and the DOM

This section is totally optional.

If you're curious, you probably noticed a index.js file with some gibberish in it.

Most boilerplates and frameworks for React that you use might mean you never need to see it or use it directly, but for a complete understanding, I'd like to share with you how your code gets to the browser.

This section will explain what that file is doing as it's the file that shows our React application in the browser.

The index. js contains the following:

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

import App from "./App";

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

root.render(<App />);

This file is connected to our index.html and is how we render the data from our application.

On line 1, you will see an import from react-dom/client.

React DOM is a package that provides DOM-specific methods to interact with the HTML DOM in a React application.

To use the createRoot function, you first need to import it from the react-dom/client package. Then, call the createRoot() function with a DOM node as its argument, where you want your React app to be rendered. Finally, use the render() method on the created root to render your React component.

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

import App from "./App"; 👈 import the App component

const rootElement = document.getElementById("root");
const root = createRoot(rootElement); 👈 createRoot and bind it to the element with id="root"

root.render(<App />); 👈 Render the app

In this example, we first import the createRoot function from the react-dom/client package and the App component from the ./App module. We then select a DOM node with the ID 'root' and create a root using the createRoot function.

Finally, we render the App component using the created root's render() method.

If this is a little confusing, don't worry!

It will usually be handled for you, and you can always come back and reference this later if you decide to try to understand this better.


In the next article, we will dive into JSX. I'll link it here after I publish it.

If you want to set up a React project article locally, you can check this article here that describes the setup using a tool called Vite.

https://www.codu.co/articles/how-to-create-a-new-react-app-with-vite-iyzulru4


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

JavaScriptTutorialReactjsLibraryFrontend
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.