Posted on Leave a comment

Installing the latest version of NodeJS – Short Guide

Windows Install

  1. Visit the official Node.js website: https://nodejs.org/
  2. Click on the “Download” button on the homepage to start the download process.
  3. Choose the appropriate package for your operating system. For example, if you’re using Windows, select the “Windows Installer” option.
  4. Run the downloaded file and follow the installation wizard instructions.
  5. Once the installation is complete, open a command prompt or terminal window and type “node -v” to verify that Node.js has been successfully installed.
  6. You can also check the version number of npm, the Node.js package manager, by typing “npm -v”

Linux Install

  1. Open a terminal window by pressing “Ctrl + Alt + T” or by searching for “Terminal” in the applications menu.
  2. Update the package list and upgrade the system packages by running the following commands:
sudo apt-get update
sudo apt-get upgrade
  1. Install the curl command-line utility if it’s not already installed by running:
sudo apt-get install curl
  1. Download and add the Node.js PPA (Personal Package Archive) to your system’s package sources list using the following command:
curl -sL https://deb.nodesource.com/setup_lts.x | sudo -E bash -

This command will download and execute a script that adds the PPA to your system.

  1. Once the PPA is added, install the latest version of Node.js and npm by running:
sudo apt-get install -y nodejs
  1. Verify that Node.js and npm have been successfully installed by running the following commands:
node -v
npm -v

These commands will display the version numbers of Node.js and npm respectively.

Congratulations, you have successfully installed the latest version of Node.js on your Debian-based Linux distribution! If you encounter any issues during the installation process, refer to the official Node.js documentation or seek help from the Node.js community.

Mac OS Install

  • Open a web browser and visit the official Node.js website: https://nodejs.org/
  • Click on the “Download” button on the homepage to start the download process.
  • Choose the appropriate package for macOS.
  • Double-click on the downloaded package file to start the installation process.
  • Follow the prompts in the installation wizard to complete the installation.
  • Once the installation is complete, open the Terminal application by searching for it in Spotlight or by navigating to Applications > Utilities > Terminal.
  • Verify that Node.js and npm have been successfully installed by running the following commands in the terminal:
node -v
npm -v

These commands will display the version numbers of Node.js and npm respectively.

Congratulations, you have successfully installed the latest version of Node.js on your macOS! If you encounter any issues during the installation process, refer to the official Node.js documentation or seek help from the Node.js community.

Posted on Leave a comment

Building a City Lookup Tool

React, React Query, and Django

Introduction:

In this tutorial, we’ll walk through creating a form that lets users select a state, county, and town using React, React Query, and Django as a backend. React will be used for building the frontend user interface, React Query for fetching and managing server-side data, and Django to create the backend API.

Prerequisites:

  • Basic understanding of React, React Query, and Django
  • Node.js and npm/yarn installed on your system
  • Python and Django installed on your system
  • Django Rest Framework ( install with pip )

Step 1: Setting up the Django Backend

1.1. Create a new Django project and app:

$ django-admin startproject myproject
$ cd myproject
$ python manage.py startapp myapp

1.2. In myapp/models.py, create the State, County, and Town models:

from django.db import models

class State(models.Model):
    name = models.CharField(max_length=100)

class County(models.Model):
    name = models.CharField(max_length=100)
    state = models.ForeignKey(State, on_delete=models.CASCADE)

class Town(models.Model):
    name = models.CharField(max_length=100)
    county = models.ForeignKey(County, on_delete=models.CASCADE)

1.3. Add ‘myapp’ to the INSTALLED_APPS in myproject/settings.py.

1.4. Run migrations to create the database schema:

$ python manage.py makemigrations
$ python manage.py migrate

1.5. Create serializers for the models in myapp/serializers.py:

from rest_framework import serializers
from .models import State, County, Town

class StateSerializer(serializers.ModelSerializer):
    class Meta:
        model = State
        fields = '__all__'

class CountySerializer(serializers.ModelSerializer):
    class Meta:
        model = County
        fields = '__all__'

class TownSerializer(serializers.ModelSerializer):
    class Meta:
        model = Town
        fields = '__all__'

1.6. Create views in myapp/views.py:

from rest_framework import generics
from .models import State, County, Town
from .serializers import StateSerializer, CountySerializer, TownSerializer

class StateList(generics.ListAPIView):
    queryset = State.objects.all()
    serializer_class = StateSerializer

class CountyList(generics.ListAPIView):
    serializer_class = CountySerializer

    def get_queryset(self):
        state_id = self.kwargs['state_id']
        return County.objects.filter(state_id=state_id)

class TownList(generics.ListAPIView):
    serializer_class = TownSerializer

    def get_queryset(self):
        county_id = self.kwargs['county_id']
        return Town.objects.filter(county_id=county_id)

1.7. Configure the API URLs in myapp/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('states/', views.StateList.as_view(), name='state_list'),
    path('states/<int:state_id>/counties/', views.CountyList.as_view(), name='county_list'),
    path('counties/<int:county_id>/towns/', views.TownList.as_view(), name='town_list'),
]

1.8. Include the app URLs in the project’s urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),
]

Step 2: Setting up the React Frontend

2.1. Create a new React project using Create React App:

$ npx create-react-app myapp-frontend
$ cd myapp-frontend

2.2. Install the necessary dependencies:

$ npm install axios react-query

2.3. Replace the contents of src/App.js with the following:

import React, { useState } from "react";
import { useQuery } from "react-query";
import axios from "axios";

const fetchStates = async () => {
  const { data } = await axios.get("/api/states/");
  return data;
};

const fetchCounties = async (stateId) => {
  const { data } = await axios.get(`/api/states/${stateId}/counties/`);
  return data;
};

const fetchTowns = async (countyId) => {
  const { data } = await axios.get(`/api/counties/${countyId}/towns/`);
  return data;
};

function App() {
  const [selectedState, setSelectedState] = useState(null);
  const [selectedCounty, setSelectedCounty] = useState(null);

  const { data: states } = useQuery("states", fetchStates);

  const { data: counties } = useQuery(
    ["counties", selectedState],
    () => fetchCounties(selectedState),
    { enabled: !!selectedState }
  );

  const { data: towns } = useQuery(
    ["towns", selectedCounty],
    () => fetchTowns(selectedCounty),
    { enabled: !!selectedCounty }
  );

  return (
    <div className="App">
      <h1>Location Selector</h1>
      <select
        value={selectedState}
        onChange={(e) => {
          setSelectedState(e.target.value);
          setSelectedCounty(null);
        }}
      >
        <option value="">Select State</option>
        {states?.map((state) => (
          <option key={state.id} value={state.id}>
            {state.name}
          </option>
        ))}
      </select>

      {selectedState && (
        <select
          value={selectedCounty}
          onChange={(e) => setSelectedCounty(e.target.value)}
        >
          <option value="">Select County</option>
          {counties?.map((county) => (
            <option key={county.id} value={county.id}>
              {county.name}
            </option>
          ))}
        </select>
      )}

      {selectedCounty && (
        <select>
          <option value="">Select Town</option>
          {towns?.map((town) => (
            <option key={town.id} value={town.id}>
              {town.name}
            </option>
          ))}
        </select>
      )}
    </div>
  );
}

export default App;

In the code above, we create the App component, import the necessary dependencies, and define three functions to fetch states, counties, and towns from the API. We then use React Query’s useQuery hook to fetch the data and store it in the component’s state. Based on the user’s selection of state and county, we conditionally render the county and town dropdown menus.

Step 3: Configure Proxy for the Development Server

To avoid CORS issues while making API requests from the frontend, add a proxy to the development server. In myapp-frontend/package.json, add the following line:

"proxy": "http://localhost:8000",

This will proxy requests made by the development server to the Django back-end running on port

Step 4: Run the Application

There is some additional code if you are running bot the Django Server and the React Server ( as below )

Make sure you have react-query installed

npm install react-query

Modify your index.js

Add an import at the beginning of your index.js

import { QueryClient } from 'react-query';

Add a new instance below the imports ( in the index.js file )

const queryClient = new QueryClient();

Wrap your ‘App’ in the QueryClient ( in the index.js file )

  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,

You index.js should now look like this:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { QueryClient, QueryClientProvider } from 'react-query';

const root = ReactDOM.createRoot(document.getElementById('root'));
const queryClient = new QueryClient();

root.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>,
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

4.1. Start the Django development server:

In the myproject directory, run the following command:

$ python manage.py runserver

This will start the Django development server on http://localhost:8000.

4.2. Start the React development server:

In the myapp-frontend directory, run the following command:

$ npm start

This will start the React development server, which will automatically open your default web browser and navigate to http://localhost:3000.

Now you should see the form with the state, county, and town dropdown menus. As you select a state and county, the corresponding counties and towns will be fetched and populated in the respective dropdowns.

Conclusion:

In this tutorial, we have demonstrated how to create a form with state, county, and town dropdowns using React, React Query, and Django. We utilized Django as our backend to serve the API, React to build the user interface, and React Query to manage data fetching and state management. This combination of technologies allows for a seamless and performant user experience while managing complex data dependencies.

Posted on Leave a comment

Getting Started with React

A Step-By-Step Tutorial

    Install Node.js and npm:

    Before you can start using React, you will need to install Node.js and npm (Node Package Manager) on your computer. Node.js is a JavaScript runtime that allows you to run JavaScript outside of a web browser, and npm is a package manager for Node.js that makes it easy to install and manage JavaScript libraries and packages. You can download and install Node.js from the official website, which will also install npm for you.

    The installation will vary depending on your operating system here are the more popular installs:

    1. Ubuntu Linux: To install Node.js on Ubuntu, open a terminal and run the following commands:
    sudo apt update
    sudo apt install nodejs
    sudo apt install npm

    The first command updates the package index on your system, the second command installs Node.js, and the third command installs npm (the Node.js package manager).

    1. Red Hat Linux: To install Node.js on Red Hat Linux, open a terminal and run the following commands:
    sudo yum update
    sudo yum install nodejs
    sudo yum install npm
    

    The first command updates the package index on your system, the second command installs Node.js, and the third command installs npm (the Node.js package manager).

    1. Apple Shell: To install Node.js on a Mac using the Terminal app, you can use either Homebrew or the official Node.js installer. Here are the commands for both options:

    Using Homebrew:

    brew update
    brew install node
    

    Using the official Node.js installer:

    NOTE: This is the preferred method in order to use the most up to date version of Node.js

    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
    nvm install node
    

    The first command installs Homebrew (if it’s not already installed), and the second command installs Node.js using Homebrew. The third command installs nvm (Node Version Manager), which allows you to manage multiple Node.js versions on your system, and the fourth command installs the latest version of Node.js using nvm.

    1. Windows PowerShell: To install Node.js on Windows using PowerShell, you can use the official Node.js installer. Here are the commands:
    Invoke-WebRequest -Uri https://nodejs.org/dist/v16.0.0/node-v16.0.0-x64.msi -OutFile nodejs.msi
    Start-Process msiexec.exe -Wait -ArgumentList '/I nodejs.msi /quiet /qn /norestart'
    

    The first command downloads the Node.js installer, and the second command installs Node.js on your system using msiexec (the Windows Installer).

    Create a new React project:

    Once you have Node.js and npm installed, you can use the “create-react-app” command to create a new React project. Open a terminal or command prompt, navigate to the directory where you want to create your project, and run the following command:

      npx create-react-app my-app

      This will create a new React project called “my-app” in the current directory, and will install all the necessary dependencies and configuration files.

      Start the development server:

      Once your React project is set up, you can start the development server by navigating to the project directory and running the following command:

      cd my-app npm start

      This will start a development server that will automatically rebuild your app whenever you make changes to the code. You can view your app in a web browser by opening http://localhost:3000.

      Understanding the project structure:

      The “create-react-app” command generates a basic project structure for you, with a few pre-built components and files. The main files you will be working with are:

      • index.html: The main HTML file that contains the root element for your React app.
      • index.js: The JavaScript file that sets up your React app and renders it into the root element.
      • App.js: The main React component that serves as the entry point for your app.

      There are also a number of other files and directories that are generated by the “create-react-app” command, such as src/index.css for your app’s CSS styles, and public/ for static assets.

        Writing your first component:

        Now that your project is set up and running, you can start writing your first React component. Open the App.js file in your text editor, and replace the existing code with the following:

        import React from 'react';
        
        function App() {
          return (
            <div>
              <h1>Hello, React!</h1>
            </div>
          );
        }
        
        export default App;
        

        This is a very simple component that just renders a heading that says “Hello, React!”. Notice that we are using JSX, which is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files.

        Rendering your component:

        Now that you have written your first component, you need to tell React to render it into the DOM. Open the index.js file in your text editor, and replace the existing code with the following:

        import React from 'react';
        import ReactDOM from 'react-dom';
        import App from './App';
        
        ReactDOM.render(
          <React.StrictMode>
            <App />
          </React.StrictMode>,
          document.getElementById('root')
        );
        

        This code imports the ReactDOM library, which is responsible for rendering your React app into the DOM, and the App component that you just wrote. The ReactDOM.render() function takes two arguments: the first is the component to render, and the second is the root element where the component should be rendered. In this case, we are rendering the App component into the root element in the index.html file.

        Adding more components:

        Now that you have successfully rendered your first component, you can start adding more components to your app. Let’s create a new component that displays a list of items. Open the App.js file in your text editor, and replace the existing code with the following:

          import React from 'react';
          
          function ItemList() {
            return (
              <ul>
                <li>Item 1</li>
                <li>Item 2</li>
                <li>Item 3</li>
              </ul>
            );
          }
          
          function App() {
            return (
              <div>
                <h1>Hello, React!</h1>
                <ItemList />
              </div>
            );
          }
          
          export default App;
          

          In this code, we have created a new component called ItemList that renders an unordered list of items. We have also updated the App component to include the ItemList component.

          Working with props:

          Components can also accept properties, known as props, that allow you to pass data into a component from its parent component. Let’s modify the ItemList component to accept an array of items as a prop, and render that list dynamically. Open the App.js file in your text editor, and replace the ItemList component with the following:

            function ItemList(props) {
              const items = props.items.map((item) =>
                <li key={item.id}>{item.name}</li>
              );
              return (
                <ul>
                  {items}
                </ul>
              );
            }
            
            function App() {
              const items = [
                { id: 1, name: 'Item 1' },
                { id: 2, name: 'Item 2' },
                { id: 3, name: 'Item 3' }
              ];
              return (
                <div>
                  <h1>Hello, React!</h1>
                  <ItemList items={items} />
                </div>
              );
            }
            
            export default App;
            

            In this code, we have modified the ItemList component to accept a prop called items, which is an array of objects that represent the items in the list. We have then used the map function to loop over the items and render a list item for each one.

            Handling Events:

            React allows you to handle user events, such as button clicks or form submissions, by attaching event handlers to your components. Let’s create a new component that displays a button and handles its click event. Open the App.js file in your text editor, and add the following code to the App component:

              function handleClick() {
                console.log('Button clicked');
              }
              
              function Button() {
                return (
                  <button onClick={handleClick}>Click me</button>
                );
              }
              
              function App() {
                return (
                  <div>
                    <h1>Hello, React!</h1>
                    <Button />
                  </div>
                );
              }
              
              export default App;
              

              In this code, we have created a new component called Button that displays a button with the text “Click me”. We have also attached an onClick event handler to the button that calls the handleClick function when the button is clicked. The handleClick function simply logs a message to the console.

              Conclusion:

              Congratulations, you have successfully created a React app and learned how to create components, render them into the DOM, work with props, and handle events. This is just the beginning of what you can do with React, and there is much more to learn. I hope this tutorial has been helpful, and happy coding!