Your First React Component: Complete Tutorial with Examples
Learn how to create and use React components, the building blocks of any React application.
Did you know that creating a React component is as simple as defining a single javascript function starting with a capital letter and returning an Html like code known as JSX?
export function ComponentExample(){
/* Javascript Logic*/
return (
/*
JSX Code
*/
)
}
Introduction
In the previous article, weβve initialized a brand new Vite project using one single command:
pnpm create vite@latest
# Or
npm create vite@latest
If youβve followed the wizard instalation steps, and selected React and Typescript Youβll get a directory structure that look like this.
We saw in the previous article, that the index.html file contains a div whose id is equal to root and imports the main.tsx file.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
The main.tsx file which is defined inside the src folder retrieves the corresponding DOM element of that div then passes it to the createRoot function that is imported from react-dom/client.
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
The createRoot function returns an object known as the root react component which points to the root div.
The root component is used to render our application components using its render method which is smart enough to go through our React components tree, convert it into Html and then inject it inside the root div.
In this article, youβll learn how you can create your own components. Either by keeping them on the same file or organizing them in multiple files.
As well as, using your components as building blocks or lego pieces which can be combined together to build any complex UI or User Interface that you can imagine.
Creating Your First React Component
So when weβve initialized a Vite project, it came with this predefined component, that was named App which weβve passed to the render function previously.
If we check its code, weβll notice that itβs a simple javascript function starting with a capital letter, and just returning an Html like code.
function App() {
const [count, setCount] = useState(0)
return (
<>
{/** more code here ... */}
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
</div>
{/** more code here ... */}
</>
)
}
Simplifying the App Component
Letβs clean this code by deleting everything inside the App function, and just return a simple container div, wrapping an h1 header, and an unordered list ol with few random list elements li.
function App(){
return (
<div>
<h1>This is my first react component</h1>
<ol>
<li>Wake up</li>
<li>Code</li>
<li>Eat</li>
<li>Sleep</li>
<li>Repeat</li>
</ol>
</div>
);
}
Creating a New Image Component
Sebsequently, we will create a new component in the same file that will return an <img/> element,
Letβs name it Image , and make it return a random image from the lorem picsum website.
function Image(){
return <img alt="Blog post image" src="https://picsum.photos/500/400" />;
}
Note that we didnβt have to use the parentheses in the
Imagecomponent because the returned code is only written in a single line, in contrast with theAppcomponent where we had to use parentheses because the code spaned more than one line.
Using the Image Component in App
Next, letβs use the image component in App, we can call it as a normal function inside of the returned html, but there is a more optimized way which using this tags syntax <Image/>.
function Image(){
return <img alt="Blog post image" src="https://picsum.photos/500/400" />;
}
function App(){
return (
<div>
<h1>This is my first react component</h1>
<Image/>
<ol>
<li>Wake up</li>
<li>Code</li>
<li>Eat</li>
<li>Sleep</li>
<li>Repeat</li>
</ol>
</div>
);
}
Running the Development Server
Now letβs run our dev server using the bellow command:
pnpm run dev
# or
npm run dev
Subsequently, we need to head into http://localhost:5173, inspect the page and check the content of the root div.
As you can see, the Html returned by the App component and its child Image component got merged together and then injected inside the root div which is defined in the index.html file.
Organizing Components into Separate Files
Okay, now itβs obvious that in a real web application you may have dozens or even thousands of components so defining them all in a single file is not practical at all, so how can we move the Image component into its own file?
First, letβs create an image.tsx file at the same directory level of the app.tsx, then just copy the Image function declaration into its own dedicated file.
Every file in Javascript is considered its own closed module. So anything that is declared there is not accessible unless we explicitly export it.
Exporting Components
There are two ways to export our component:
- We can add the export keyword next to it, and then import it in
app.tsxlike this:
image.tsxfile.
export Image;
app.tsxfile
import {Image} from './image.tsx'
- Or by adding a unique
default exportstatement at the end of the file followed by the function name, then import it like this:
image.tsxfile.
export default Image;
app.tsxfile.
import Image from './app.tsx'
The advantage of the first approach is being able to export more than one declaration from a single file, so we could have created another component called <Image2>, imported it in app.tsx then used it inside of the returned Html like code.
Final Note
Finally, Iβd like to add one important note which isβ¦
Never and never declare a component inside of another component like this, because it wonβt be cached and optimized by react and your app will get slower.
export function App(){
// β
function SubComponent(){
return (
<div>{/* code... */}</div>
)
}
return ( /*code...*/);
}
Conclusion
Html files can get really big, and just making sure that tags are closing properly is honestly a big drag.
React takes a modular approach by dividing the problem of building a complex interactive web pages, into smaller sub-problems or building blocks known as components.
In this article, weβve learned everything you need to create your first components, organize them in multiple files and nest them or combine them as needed to create any kind of complex ui.
In the next article we will reveal more secrets π€« about the html kind of code returned by every React component π.
See you then and happy coding.