Introduction to React Components

Introduction to React Components

 

In this article, we will learn about React components. Components are independent and reusable bits of code that help you build UIs efficiently. They serve a similar purpose as JavaScript functions but work in isolation and return HTML elements.

 

React components come in two types: Class components and Function components. In this tutorial, we will focus on Function components.

 

Setting Up Your React App

If you haven't created a React app before, don't worry! You can follow this detailed guide to get started:

https://www.rsinnovators.com/blog/create-react-hello-word-app-with-typescript-10051

 

Cleaning Up App.tsx

First, open your App.tsx file and remove all existing HTML. Replace it with the following code:

<div className="App">
  <div className='App-header'>
    <h1>Welcome to React!</h1>
  </div>
  <div>
    <h1>Home Page</h1>
  </div>
  <div>
    <h3>I am footer</h3>
  </div>
</div>
  

If you run the app now, you will see the header and footer displayed along with the home page content. However, we want the header and footer to be reusable across all pages. React components make this easy.

 

Creating the Header Component

Create a new folder named components in your project root. Inside it, create a file called Header.tsx. Add the following code to define the Header component. Follow similar steps to create the Footer component.

import { FC } from "react";

const Header: FC = () => {
  return (
    <div className='App-header'>
      <h1>Welcome to React! from component</h1>
    </div>
  );
}

export default Header;
  

Using the Header Component in App.tsx

Now, import the Header component into your App.tsx file and use it like this:

import Header from './components/Header';

function App() {
  return (
    <div className="App">
      <Header />
      <div>
        <h1>Home Page</h1>
      </div>
      <div>
        <h3>I am footer</h3>
      </div>
    </div>
  );
}

export default App;
  

export default Header; is a way to export the Header component from its file so that it can be imported and used in other files in your React project.

 

By creating components like Header and Footer, you can easily reuse them on multiple pages without duplicating code.

 

Looking Ahead: Passing Props to React Components

In the next blog, we will explore how to make your React components even more flexible and powerful by passing props (properties). Props allow you to send data from a parent component to a child component, making your UI dynamic and customizable.

 

You’ll learn how to:

    • Define props in function components with TypeScript

    • Pass data like strings, numbers, or objects to components

    • Use props to display dynamic content inside components

Stay tuned to level up your React skills!