How I built my first Project with React Hooks

How I built my first Project with React Hooks

Hey, you made the right choice, you want to be a software engineer speaking the language of one of the best frameworks of the century – React.js. Software engineering is not more about cramming frameworks and syntaxes – it’s a tool for solving problems and you get better through constant practice.

React is a JavaScript Library for building interactive user Interfaces, learn more about React here.


Basic Concepts in React

Before we continue, let's walk through some of the important fundamental concepts in react.js that will help us build the project. These include Components, State, React Hooks, Props, and Functional components.

  1. Components: Components are the core building blocks of React applications. They contain independent, reusable code. Using components you can split the user interface into separate parts. You can then reuse those parts and work with them independently. React Components are so useful because they can save you a lot of time. It keeps you DRY (don't repeat yourself)!

  2. State: In React, the state of a component can be represented by data stored in an object. This allows components to manage and update their own data. A component's state determines how it renders and behaves. In other words, “state” is what allows you to create components that are dynamic and interactive.

  3. Props: Props —short for "properties"— are used to pass data from a parent component to a child component. Props are one of the integral parts of React and you can use props to perform several operations in React.

  4. Functional Component: React's Functional component is simply a JavaScript function that accepts props as an argument and returns a React element (JSX).

  5. Hooks: React Hooks are built-in functions that allow you to manage state and other React features like lifecycle methods inside functional components. They can also help you to write concise and clear code.

    You can learn more about React from the video given below

    %[youtu.be/dpw9EHDh2bM]

  6. JSX: JSX (JavaScript XML) is also very important. it is a syntax extension to JavaScript. React is really an interesting framework as it allows writing both HTML and JavaScript in the same file, so we don’t need to create a separate HTML file.

    JSX creates elements that you want to render. Simply put rendering is a process to show the elements in the browser. Learning constantly is a must for every software developer at every level. You can check this documentation to read more about JSX

Enough of the basics, let's hit the ground running!

Project Requirements

If you are new to coding and React or need a refresher, I would recommend you to read this article “Create your very first React App” to get a nice refresher on the tools and resources required to get started with this.

Ok, let's reach for the stars!

Step 1. Install Node.js

You need to check if you already have the latest version of NodeJS installed, you can use the command line below to check if you have node installed.

node -v

This should print the version number, so you will see something like (v16.17.1) if you do not have node installed, then follow the instructions in this article.

Step 2. Create React App

Now, add the below command Line on your Terminal to create a new app within a new directory with a name of your choice. I used exam-semester2 in this react project article.

cd Desktop
mkdir React
cd React
npx create-react-app exam-semester2
cd exam-semester2

Hint: Execute the code, one line at a time.

npx stands for Node Package Execute. It is a package runner that comes with the npm that enables users to execute any package directly without installation. The mkdir command is used for creating a new directory. The cd command is a command-line shell command used to change the current working directory, by typing cd exam-semester2 changed the working directory to exam-semester2

It will take a couple of minutes to install the dependencies.

WHERE DO WE GO NEXT?

Remember, this is a semester examination project with multiple parts. Each of these parts will be implemented using unique or separate React Components Let's highlight all the components before we get into actual coding. I love writing the features I want to implement in my project so I can create the components of the project one at a time. Senior and more experienced developers structure their projects with the right hierarchy and naming conventions to make the code clean and readable.

The component files are shown in the screenshot above. These include boundary.jsx, Home.jsx, Layout.jsx, MyCounter.jsx, Page404.jsx, Reducer.jsx and seo.jsx

Step 3: Setting Up the Project

Run the following command to create the app:

npx create-react-app exam-semester2

This will create a new react app, and we can now start building. It will generate a file system structure with several files and folders.

Run the following command in the terminal to start the development server:

npm start

After a few minutes, the command should open a new tab in your browser, pointing to http://localhost:3000. All the changes that you'll make to the project will be automatically updated here.

Step 4: Creating the Skeleton of the project

Open the src/App.js file and delete all the by-default code that's present there. Now replace the default with the following code:

import { useState } from "react";

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

let incrementCount = () => { 
    setCount(count + 1); };

let decrementCount = () => { 
    setCount(count - 1); };

const handleChange = (event) => { setCount(parseInt(event.target.value)) console.log("value is:", event.target.value); };

return (
    <div className="app">   
      <div className="page-design">
        <div class="count-card">
          <h2>Count (UseEffect):</h2>
          <h3>{count}</h3>

        </div>
      </div>
    </div>
  );
}

The first statement imports the useState hook from the react module. The hook is used to create the count state which is initialized to 0. The value of the count is changed using the setCount function.

You'll use the incrementCount, decrementCount, and setCount functions to increase, decrease, and reset the value of the counter.

You may notice the curly brackets { } used around the count variable in the markup. This essentially lets the JSX parser know that it should treat the content inside those braces as JavaScript.

setCount (count + 1) is used for increasing the count by 1

setCount (count - 1) is used for decreasing the count by 1

Step 5: Let's power our counter (add functional buttons!)

You need to create three buttons to implement the functionality of the counter application: the decrement count button, increment count button, and reset button. We will now add the following code below:

<div class="buttons">
            <button className="button-3" onClick={incrementCount}>
              {" "}
              Increment{" "}
            </button>
            <button className="button-2" onClick={decrementCount}>
              {" "}
              Decrement{" "}
            </button>
            <button className="button-1" onClick={() => setCount(0)}>
              {" "}
              Reset{" "}
            </button>
</div>

OnClick event occurs when the user clicks on an element, when the user clicks the buttons the given function then executes. For example, when clicking the "Increment" button, function incrementCount() will execute and the state count should increase by 1. When the user clicks "Reset" button, setCount(0) function will execute and the number will return to 0. Similarly, when pressing the "Decrement" button, function decrementCount() will execute and the state count should decrease by 1.

Notice how these functions given to onClick event are missing the parenthesis (), this is because we do not want to call the function right away. You have to omit the parentheses if you want to pass the function to other code so it can call the function, in this example the onClick event handler where the function should be called in the future when the click event occurs.

I styled the three buttons differently and maintained a similar style for the buttons across the project using the code below

import "./App.css";

"./" means the CSS file is in the same hierarchy level as the App.js file (they are in the same folder or path).

Congratulations! You have successfully built a counter app with React...

NAVIGATION

Now, let's go over the Navigation structure of the React project. All the pages can be accessed from the Navigation bar available on all the pages.

Step 1: Install React Router

npm install react-router-dom v6

Watch this video

https://youtu.be/Jppuj6M1sJ4

Step 2: Configuration of Routes

Now that we have react Router installed, we will add the routes to the pages in our project.

Import the following components of react-router-dom inside this js file.

  • BrowserRouter

  • Route

  • Routes

1

import {

Also, import all the components that need to be returned within each route.

Step 3:

Wrap the content of the App component within the <BrowserRouter>.