Getting Started with React: Creating Your Own Blog App - Part 1

Discover the Power of React by Building a Blog App: A Project-Based Learning Approach

Getting Started with React: Creating Your Own Blog App - Part 1

Introduction πŸ™‹

This article is not a standalone piece that teaches you what React is and how to work with it. Instead, this is a blog series dedicated to learning React and its concepts.

ReactJS is the most beloved JS framework today. If you are a frontend developer, you know why React is suitable for small to large scale applications. However, determining the best frontend framework in the market remains a debatable question.

Many people consider React to be subpar. Each frontend framework has its own advantages and disadvantages, which leads people to either like or dislike them. However, today we are not comparing any frontend frameworks; instead, we are going to learn React through project-based learning.

What is this series about 🀩 ?

A study conducted in 2000 revealed that when individuals learn by creating something, they have the opportunity to solve problems, collaborate, and develop critical thinking and problem-solving skills. This approach aligns with the principles of project-based learning.

We will use the same approach to learn React by building a simple Blog App. This series focuses on learning through building, following the principles of project-based learning. I find this to be the best way to learn any language or framework in tech because you grasp the concepts of the language or framework while simultaneously solving real-world problems.

Whenever you encounter a problem that requires a solution in any language or framework, you'll know how to address it effectively and in the best way possible to meet your needs.

What app are we building in this series πŸ€” ?

Many people prefer learning through watching videos, online courses, reading documentation, or browsing blogs. Some blogs feature lengthy tutorials that may cause readers to lose interest halfway through, as extended periods of reading can become unengaging. That's why online courses often divide their content into sections or topics, preventing boredom and encouraging learning through the completion of chapters.

Upon completing a section or topic in an online course, you feel a sense of achievement. This fuels your motivation and encourages you to continue learning. That's why I've divided this blog into a series, covering everything from development to deployment, to facilitate learning in a more engaging manner.

In this series, you will be learning through blog posts. So, let's create a simple blog app.

P.S. I did not design this app, I found the image through a Google search. If anyone knows the designer, I would be more than happy to give them credit in this blog.

Prerequisites

  • Familiar with HTML & CSS

  • Proficiency in Vanilla JavaScript

  • Any Code Editor

  • Nodejs Installed on the system

Let's begin

Without further ado, let's address the most fundamental question that beginners often ask.

What is React?

React is an open-source JavaScript library for building user interfaces. These interfaces are designed using atomic, reusable components that can be utilized in different or the same sections or pages.

You can build applications for various platforms using React, but it is primarily used for creating Single Page Apps, Mobile Apps with React Native, and Desktop Apps with Electron. As of 2022, it is the most popular web framework. (sorry Angular and Vue fans πŸ˜…).

A great way of working with React is by breaking down the design into wireframes. This makes it easy to map components and their hierarchy for our application. Here we can identify a minimum of Header, SearchBar, List, ListItem, and Homepage components, among which Header and Homepage components can be used in many places with dynamic content, hence making our life easier when we actually start to build the app.

The following are the most important methods/tools that are used when working with React apps:

JSX (JavaScript XML)

Reacts apps are written in JSX (you can write them with pure JavaScript, but rarely you’ll see devs do that since it's a pain to work with it). JSX syntax looks identical to that of HTML’s but in reality, it is just a syntactic sugar for creating React elements.

Babel

The purpose of a web browser is to display web pages, but since our React app is written in JSX, it cannot be understood by any web browser. So how will our web page be displayed in a browser? Well, that’s where Babel comes into play. Babel is an open-source JavaScript compiler and transpiler which is used with React apps to transform our JSX code into plain JavaScript.

Node Package Manager (npm)

npm is a package manager that comes out of the box when you install Node.js. It helps us manage a project/app (any JavaScript app to be precise) by keeping track of dependencies (packages) and their version in a package.json file. It also lets us write scripts in the package.json file, which can be executed to perform certain tasks such as building our app for production or running automated tests to check if our app is still working fine.

Let's create React APP using VITE πŸ§‘β€πŸ’»

Before we go to creating a react app, let me tell you about VITE. why we are using VITE instead of just npx create-react-app my-app command?

FYI what NPX is?: The npx stands for Node Package Execute and it comes with the npm, It is an npm package runner that can execute any package that you want from the npm registry without even installing that package. The npx is useful during a single time use package.

create-react-app uses a Webpack under the hood. The Webpack bundles the entire application code before it can be served. With a large codebase, it takes more time to spin up the development server, and reflecting the changes made takes a long time.

Here VITE comes into the picture and saves a lot of our time. Vite is a next-generation, front-end tool that focuses on speed and performance. It is a build tool for React applications that offers faster development times and build speeds compared to Create React App.

Vite's production builds are done using Rollup, which is faster than Webpack used by CRA. This means Vite builds tend to be 2-10x faster, especially for larger apps. As React apps grow, CRA's performance deteriorates due to the entire application rebuild on changes. Vite scales better since only changed modules are rebuilt.

Vite pre-bundle dependencies only once, and then serves them from cache. CRA rebuilds dependencies on every change. This results in better performance for Vite apps.

In summary, Vite offers significantly faster development and build times for React apps compared to CRA, especially for larger apps. The major trade-off is a slightly steeper learning curve due to differences in configurations. But for most projects, the benefits of Vite make it a good alternative to CRA.

You can learn about VITE in docs πŸ‘‰ VITE DOCS.

Now that you're familiar with the essential concepts of React, it's time to dive in and create a React application.

Step 1: Create a new VITE project

Run the following command in your terminal to scaffold a new Vite project:

npm create vite@latest

Step 2: Follow the prompts

This will ask you to install the create-vite package. Type y the press Enter

Step 3: Enter the Project Name

Once you install the vite package, then it will ask you to Type your project name.

Step 3: Select a Framework

Vite supports all major front-end frameworks, even you can use Vite with vanilla javascript as well.

Here you need to select React as we are learning React in this blog series. You can use arrow keys to navigate between framework lists. Once you select the React framework, press Enter.

Once you are used to Vite, then after you can use the power of Vite in any front-end framework.

Step 4: Select a variant

You can build React apps using Typescript as well. We are not using typescript in this blog series, we are just using javascript to make things easier for you.

Here, you can use arrow keys to navigate between variant lists. Once you select the Javascript variant, press Enter.

You might know what typescript is, it's a strongly typed, object-oriented, compiled programming language that builds on JavaScript. But one question that might arise for you is what is Javascript + SWC and Typescript + SWC ?

SWC (stands for Speedy Web Compiler ) is a super-fast TypeScript / JavaScript compiler written in Rust. It is designed to be a drop-in replacement for Babel. It uses a Rust-based parser and a JavaScript-based compiler to achieve faster compilation times than Babel.

Step 5: Congratulations πŸŽ‰

once everything goes well then you will be able to see this below screen.

If you encounter any issues, you can consult the official Vite troubleshooting documentation πŸ‘‰ TroubleShooting DOCS

Step 6: Install the dependency

To install the dependency you need to run the command

npm install

By running this command it will install all the necessary dependencies that require to run the app. Once it is installed you will able to see a folder named node_modules, this folder has every installed need for your project.

Step 6: Run your APP

By simply running the following command

npm run dev

Hopefully, you didn't encounter any errors. Once your app runs successfully, it should appear like this:

Now give yourself a pat on the back, as you've just created a React app using Vite.

Next, let's explore the file structure of this project. Open up the project in your favourite code editor, which is VS Code πŸ˜›

The files and folders in the React + Vite project will appear as follows. I will explain each file as seen below.

  • src/: This is the main source code folder. All your JSX, CSS, and other assets will live here.

  • src/assets/: This folder contains static assets like images, fonts, etc.

  • App.jsx: This is the main app component that renders your page components.

  • main.jsx: This is the entry point for your app. It renders the App component.

  • index.css: This contains global styles for your app.

  • App.css: This contains App.jsx styles for your App.jsx component.

  • vite.config.js: This contains your Vite configuration.

  • package.json: This is one of the most important files in any React project. It contains important information about your project such as its name, version, dependencies, scripts, etc.

  • .gitignore: This tells Git which files and folders to ignore i.e. not track and not include in your commits.

  • .eslintrc.cjs: This format is used when your project specifies "type":"module" in the package.json file, indicating an ESM (ECMAScript Module) package.

Let's see what's in the code 🚧

Main.jsx file

Let's dive deep into what is in the main.jsx file. This is the main entry point that serves as the main starting point for the React application.

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

1️⃣ Importing the necessary dependencies:

  • The first line imports the React library, which is the core library for building React components and managing their state.

  • The second line imports ReactDOM from the react-dom/client module. ReactDOM is responsible for rendering React components into the DOM (Document Object Model).

  • The third line imports the App component from the App.jsx file. The file extension .jsx indicates that this is a JavaScript file containing JSX code, which is a syntax extension for React.

  • The fourth line imports a CSS file named index.css, which likely contains styling rules for the components used in the application.

2️⃣ Rendering the root component:

  • The ReactDOM.createRoot the method is used to create a root React component. The document.getElementById('root') expression retrieves the DOM element with the ID 'root', which serves as the container for our React application.

  • The render method is then called on the root component to render the JSX code.

  • The JSX code inside the render method represents the structure of the application.

  • <React.StrictMode> is a wrapper component provided by React that helps identify potential issues in the application during development. It performs additional checks and warnings to help catch common mistakes.

  • <App /> is a JSX syntax that represents the App component. This component will be the root component of our application and will be rendered inside the root element in the DOM.

App.jsx

This file renders a webpage with the Vite and React logos, a counter button, and some text.

You find code something like this. Some changes might be there as the version changes but concepts will remain the same.
Let's dive into the code and see what it is doing.

import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

function App() {
  const [count, setCount] = useState(0)

  return (
    <>
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
        <p>
          Edit <code>src/App.jsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </>
  )
}

export default App

1️⃣ Importing necessary modules and files:

  • The import { useState } from 'react' line is importing the useState function from the 'react' module. The useState function is a special function provided by React that allows us to create and manage state variables.

  • The reactLogo and viteLogo variables are importing image files. These images will be used later in the component.

  • The import './App.css' line is importing a CSS file called 'App.css' that contains styles specific to this component.

2️⃣ Defining the App component:

function App() {
  // ...
}
  • Here, we are defining a function called App which represents our component.

3️⃣ Declaring a state variable:

const [count, setCount] = useState(0)
  • The useState function is used to declare a state variable named count and its corresponding update function setCount. In this case, the initial value of count is set to 0. In our next blog, we will dive deeply into the useState hook.

4️⃣ Building the component's JSX (JavaScript XML) structure:

return (
  <>
    {/* JSX code */}
  </>
)
  • The return statement is used to define the structure of the component using JSX. JSX allows us to write HTML-like code within JavaScript.

5️⃣ JSX code:

  <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
        <p>
          Edit <code>src/App.jsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
  • This JSX code represents the structure of the component. It consists of several HTML elements with different classNames and some dynamic values.

  • In our next blog, we will dive deeply into the className attribute. In short, className is simply the class attribute in an HTML tag. We can't use "class" in JSX because it is a reserved keyword in JavaScript.

6️⃣ Handling a button click event:

<button onClick={() => setCount((count) => count + 1)}>
          count is {count}
</button>
  • This code defines a button element. When the button is clicked, the onClick event is triggered, and it calls a function that updates the count state variable using the setCount function. The new value of count is obtained by adding 1 to the current value. The text inside the button shows the current value of count

7️⃣ Exporting the component:

export default App;
  • Finally, the App component is exported, allowing it to be used in other parts of the application.

So, that's it for the code. We will dive deeper when we build our blog app.

What's Next?

In the next blog, we will begin implementing the header and footer sections and adding routing to our app. Routing is crucial in any application, as it enables users to navigate between pages either by manually clicking on a button or link, or by programmatically routing to other pages.

Conclusion

In conclusion, this blog series aims to teach React through a project-based learning approach by building a simple blog app. We have set up a React project using Vite for faster development and better performance.

In the upcoming articles, we will implement various sections of the app, including the header, footer, and routing. Stay tuned for more hands-on learning as we dive deeper into React and build our blog app together.

Thank you for reading my article. Feel free to comment and share your suggestions or thoughts.

Also, Follow me on Twitter or Linkedin I share Cloud, System Design, Code, and many more tech stuff 😊

Resources

Did you find this article valuable?

Support Pradhuman Blog by becoming a sponsor. Any amount is appreciated!

Β