Categories
frontend javascript web development

JavaScript methods for finding elements

Hey guys,

Welcome back to a new article !

In this article, we will learn about different JavaScript methods that we can make use of for finding elements in an array. Arrays, as we know, is a data structure that is one of the key building blocks that we make use of for building data-based intensive web applications. With an array, we can easily store and manipulate elements within the array as and how we want to. Let us see the 4 methods that you can make use of for finding an element in an array.


find

The find() method returns the first element in the provided array that satisfies the provided testing function. So we specify a testing function as the callback and the find method will return the first item that returns true for the condition that we test within the specified callback. If no elements satisfy the testing function, then undefined gets returned. Let us see an example for the find method.

const numbers = [5, 12, 8, 130, 44];

const firstNumberGreaterThan10 = numbers.find(element => element > 10);

console.log(firstNumberGreaterThan10 );
// expected output: 12

findIndex

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. So as a testing function, we pass a callback to the findIndex method and there we explicitly mention a condition and based on the truthiness of that condition, we get an element that satisfies that specified condition. In case, no element passes the testing condition then it returns -1.

const numbers = [1, 3, 4, 6, 10];

const greaterIndex = numbers.findIndex(element => element > 6); 
console.log(greaterIndex); // 4

const smallerIndex = numbers.findIndex(element => element > 10); 
console.log(smallerIndex); // -1 

Consider the above example in which we have a list of numbers that is given to us, let us say we want to find the index of the first occurrence of an element which is greater than 6. So for this case, we can make use of the findIndex method with the testing condition as element > 6. Next, let us say we want to find the index of the first occurrence of an element which is greater than 10. So we again make use of the findIndex method with the testing condition as element > 10. Now since there is no element that satisfies the above condition, hence we get a -1 for this.


indexOf

The indexOf() method returns the index of the first occurrence of the substring or element that we specify as the argument.

Let us see an example for the indexOf method, let us say we are given an array of elements and we want to find the index of some elements within that array. So see the below code :

const numbers = [1, 3, 4, 6, 10];

const indexOf10 = numbers.indexOf(10); // 4

const indexOf16 = numbers.indexOf(16); // -1

So if we try to search the index of the number 10 in the given array of numbers, then we get 4 because 10 is sitting at index 4 of the given array. Next, for the number 16 we get -1 because the number 16 is not present anywhere within the given array.


lastIndexOf

The lastIndexOf() method returns the index of the last occurrence of the specified substring or element that we specify as argument. The lastIndexOf method is similar to the indexOf method that we just discussed but the only difference being that it starts to look up from the trailing end of the array instead of the start of the array like we do in indexOf. So in essence, if you know for sure that the element that you are looking for lies in the latter half of the array, then using the lastIndexOf method makes more sense.

const numbers = [1, 3, 4, 6, 10];

const indexOf10FromLast = numbers.lastIndexOf(10); 

console.log(indexOf10FromLast); // 4

const indexOf16FromLast = numbers.lastIndexOf(16); 

console.log(indexOf16FromLast); // -1

So in above example, if we try to find the index of the last occurrence of a particular element, say 10, then we get 4. Since, 10 is present at index 4 and we only have one occurrence of 10 in the numbers array. Next, 16 is not present anywhere in the array so for that if we try to find the last occurrence of it using the lastIndexOf method, we get -1.


So this is it for this article. Thanks for reading.

Categories
frontend javascript reactjs

Demystifying the useReducer Hook in 5 minutes

In this video, we will learn about a very important hook which is the useReducer hook.

Categories
frontend javascript reactjs

Demystifying the useEffect hook in under 13 minutes

In this video, we will learn about the useEffect hook in great detail and we will cover all the cases for the useEffect hook that one faces while working on a React app.

Categories
frontend javascript reactjs

Demystifying the useState hook in under 10 minutes

In this video, we will learn first about the basic Hooks that we have in React namely the useState and the useEffect hook. Once we understood the bare basics of the need for Hooks, then we will start to learn about the useState hook.

Categories
backend database frontend javascript mongodb web development

New FULL Web Developer Course on YouTube

I decided to create a full Web Developer Course that will cover all the technologies that you need to kickstart your Full Stack Developer Journey. No bullshit, everything practical and relevant will be covered.

We will delve into following topics –

  1. HTML
  2. CSS
  3. JavaScript
  4. Node.js
  5. MongoDB

Check out the first video of this series where we cover the introduction to World Wide Web and the Evolution of the World Wide Web. The code for the video (if any) can be found on GitHub.

⭐ Check out the 10 JavaScript Projects in 2 Hours Video of my JavaScript Series where we build 12+ Projects using JavaScript :

Follow me on:
👉 Twitter: https://twitter.com/The_Nerdy_Dev
👉 Instagram: https://instagram.com/thenerdydev

Categories
frontend javascript reactjs

Create your own Exercise Planner using React.js [Complete Code]

Hey everyone 👋🏻,

In this article, let us see how we can build an Exercise Planner Application using React.js.

✏ Demo for the Project & Initial Setup

So the first thing you need to do is to create a new project.
Make sure to install Node.js onto your system because we will be needing that for our project.

We will be using this tool for creating a new React Project :

Create React App :

image

Install Node.js :image

Create a new React Project

// To create a new React Project 
npx create-react-app <project_name>
cd <project_name>
// To run the project 
npm start

Install React Router DOM package

npm install react-router-dom 

Install JSON-server package globally

We will be using JSON-server for our project.

npm install json-server -g

Create a new file – exercises.json

This is the file that will contain all the exercises that we will be needing in this application. This file will serve as a local JSON store for our application.

store/data.json

{
  "exercises": [
    {
      "title": "Pushups",
      "details": "Pushups are beneficial for building upper body strength. They work the triceps, pectoral muscles, and shoulders. When done with proper form, they can also strengthen the lower back and core by engaging (pulling in) the abdominal muscles",
      "complete": false,
      "id": 119
    }
  ]
}

Inside a new terminal, run the json-server by running the command

json-server -g ./src/store/data.json --watch --port=3111

Complete Code 👨🏻‍💻

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

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

// 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();

App.jsx

import {Switch, Route } from "react-router-dom"
import HomePage from './pages/HomePage';
import './App.css';
import CreateExercise from "./pages/CreateExercise";
import Navbar from "./components/Navbar";
import EditExercise from "./pages/EditExercise";

function App() {
  return (
    <div className="App">
      <Navbar />
      <Switch>
        <Route path="/home" exact>
          <HomePage />
        </Route>
        <Route path="/create-exercise" exact>
          <CreateExercise />
        </Route>
        <Route path="/exercises/:id/edit">
          <EditExercise />
        </Route>
      </Switch>
    </div>
  );
}

export default App;


App.css

.App {
  text-align: center;
}

index.css

html {
  --pink: #D60087;
  --golden: goldenrod;
  --green: rgba(216, 235, 48, 0.83);
  --text-shadow: 2px 2px 0 rgba(0,0,0,0.2);
  font-size: 62.5%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  box-sizing: border-box;
}

*, *:before, *:after {
  box-sizing: inherit;
}

body {
  font-size: 2rem;
  line-height: 1.5;
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' version='1.1' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:svgjs='http://svgjs.com/svgjs' width='1440' height='560' preserveAspectRatio='none' viewBox='0 0 1440 560'%3e%3cg mask='url(%26quot%3b%23SvgjsMask1000%26quot%3b)' fill='none'%3e%3crect width='1440' height='560' x='0' y='0' fill='%230e2a47'%3e%3c/rect%3e%3cpath d='M136.72 348.61a22.94 22.94 0 1 0 43.22-15.38z' stroke='%23e73635'%3e%3c/path%3e%3cpath d='M511.55 165.45L536.61 165.45L536.61 190.51L511.55 190.51z' stroke='%23037b0b'%3e%3c/path%3e%3cpath d='M483.33 455.66 a20.42 20.42 0 1 0 40.84 0 a20.42 20.42 0 1 0 -40.84 0z' fill='%23e73635'%3e%3c/path%3e%3cpath d='M1228-20.28a48.24 48.24 0 1 0-63.63 72.52z' stroke='%23037b0b'%3e%3c/path%3e%3cpath d='M1392.69 128.01 a29.96 29.96 0 1 0 59.92 0 a29.96 29.96 0 1 0 -59.92 0z' stroke='%23d3b714'%3e%3c/path%3e%3cpath d='M1076.84 554.49L1113.49 554.49L1113.49 591.14L1076.84 591.14z' stroke='%23d3b714'%3e%3c/path%3e%3cpath d='M756.26 7.46L795.56 7.46L795.56 35.82L756.26 35.82z' fill='%23d3b714'%3e%3c/path%3e%3cpath d='M25.99 370.04L26.54 370.04L26.54 423.32L25.99 423.32z' fill='%23d3b714'%3e%3c/path%3e%3cpath d='M905.99 522.28 a27.93 27.93 0 1 0 55.86 0 a27.93 27.93 0 1 0 -55.86 0z' stroke='%23d3b714'%3e%3c/path%3e%3cpath d='M878.82 241.19L928.56 241.19L928.56 290.93L878.82 290.93z' fill='%23e73635'%3e%3c/path%3e%3cpath d='M620.67 145.35L648.93 145.35L648.93 173.61L620.67 173.61z' stroke='%23037b0b'%3e%3c/path%3e%3cpath d='M941.34 228.22a0.43 0.43 0 1 0-0.84 0.22z' stroke='%23e73635'%3e%3c/path%3e%3cpath d='M142.87 85.55 a19.16 19.16 0 1 0 38.32 0 a19.16 19.16 0 1 0 -38.32 0z' stroke='%23037b0b'%3e%3c/path%3e%3cpath d='M329.59 523.81L381.54 523.81L381.54 575.76L329.59 575.76z' fill='%23e73635'%3e%3c/path%3e%3cpath d='M794.97 148.48 a17.04 17.04 0 1 0 34.08 0 a17.04 17.04 0 1 0 -34.08 0z' stroke='%23d3b714'%3e%3c/path%3e%3cpath d='M1144.93 501.44a3.73 3.73 0 1 0-6.24 4.09z' stroke='%23e73635'%3e%3c/path%3e%3cpath d='M1.85 326.79L6.52 326.79L6.52 331.46L1.85 331.46z' fill='%23d3b714'%3e%3c/path%3e%3cpath d='M1161.24 414.19L1165.88 414.19L1165.88 445.98L1161.24 445.98z' fill='%23e73635'%3e%3c/path%3e%3cpath d='M1208.54 452.49a10.52 10.52 0 1 0 10.48 18.25z' fill='%23e73635'%3e%3c/path%3e%3cpath d='M1356.2 405.97a49.06 49.06 0 1 0 59.45-78.06z' stroke='%23037b0b'%3e%3c/path%3e%3cpath d='M569.26 204.09 a47.56 47.56 0 1 0 95.12 0 a47.56 47.56 0 1 0 -95.12 0z' stroke='%23d3b714'%3e%3c/path%3e%3cpath d='M955.59 150.05a43.84 43.84 0 1 0-65.58-58.2z' stroke='%23e73635'%3e%3c/path%3e%3cpath d='M827.49 284.25L864.82 284.25L864.82 321.58L827.49 321.58z' stroke='%23d3b714'%3e%3c/path%3e%3cpath d='M718.92 539.64 a45.27 45.27 0 1 0 90.54 0 a45.27 45.27 0 1 0 -90.54 0z' fill='%23d3b714'%3e%3c/path%3e%3cpath d='M1253.87 200.13L1273.78 200.13L1273.78 220.04L1253.87 220.04z' fill='%23e73635'%3e%3c/path%3e%3cpath d='M365.3 8.63L376.7 8.63L376.7 16.04L365.3 16.04z' stroke='%23e73635'%3e%3c/path%3e%3cpath d='M691.18 292.33a16.5 16.5 0 1 0 0.63-33z' fill='%23037b0b'%3e%3c/path%3e%3cpath d='M224.16 500.66L270.06 500.66L270.06 546.56L224.16 546.56z' fill='%23e73635'%3e%3c/path%3e%3cpath d='M174.91 13.36 a25.6 25.6 0 1 0 51.2 0 a25.6 25.6 0 1 0 -51.2 0z' stroke='%23037b0b'%3e%3c/path%3e%3cpath d='M1396.28 502.2 a16.58 16.58 0 1 0 33.16 0 a16.58 16.58 0 1 0 -33.16 0z' fill='%23037b0b'%3e%3c/path%3e%3cpath d='M1337.35 217.49L1380.42 217.49L1380.42 268.22L1337.35 268.22z' fill='%23d3b714'%3e%3c/path%3e%3cpath d='M429.47 162.98a54.75 54.75 0 1 0 89.11 63.64z' fill='%23d3b714'%3e%3c/path%3e%3cpath d='M56.44 369.3L67.51 369.3L67.51 397.03L56.44 397.03z' stroke='%23e73635'%3e%3c/path%3e%3c/g%3e%3cdefs%3e%3cmask id='SvgjsMask1000'%3e%3crect width='1440' height='560' fill='white'%3e%3c/rect%3e%3c/mask%3e%3c/defs%3e%3c/svg%3e");

}
:focus {
  outline-color: var(--pink);
}

Components

components/BaseFilter.css

 .filter-nav button {
    background: none;
    border: none;
    color: #bbb;
    outline: none;
    font-size: 15px;
    text-transform: uppercase;
    margin-right: 10px;
    letter-spacing: 1px;
    font-weight: bold;
    cursor: pointer;
  }
  .filter-nav button.active {
    color: goldenrod;
  }

components/BaseFilter.jsx

import React from "react";
import './BaseFilter.css';
const BaseFilter = (props) => {

    <nav className="filter-nav">
      <button
        onClick={() => props.onUpdate('all')}
        className={props.current === 'all' ? 'active' : ''}
      >
        View all
      </button>

      <button
        onClick={() => props.onUpdate('completed')}
        className={props.current === 'completed' ? 'active' : ''}
      >
        Completed
      </button>

      <button
        onClick={() => props.onUpdate('pending')}
        className={props.current === 'pending' ? 'active' : ''}
      >
        Pending
      </button>
    </nav>
  );
};

export default BaseFilter;

components/ExerciseItem.jsx

import React from 'react'
import { Link } from 'react-router-dom';

import './ExerciseItem.css';

function ExerciseItem(props) {

  const performExerciseDeletion = () => {

    fetch(`http://localhost:3111/exercises/${props.exercise.id}`, {
      method: 'DELETE',
    })
      .then(() => props.onDeleteExercise(props.exercise.id))
      .catch((err) => console.log(err));

  };

  const performExerciseCompletion = () => {
    fetch(`http://localhost:3111/exercises/${props.exercise.id}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ complete: !props.exercise.complete }),
    })
      .then(() => props.onCompleteExercise(props.exercise.id))
      .catch((err) => console.log(err));

  };
  const classes = ['exercise'];
  if (props.exercise.complete) {
    classes.push('complete');
  }
  return (
    <div className={classes.join(' ')}>
      <div className="actions">
        <h4>{props.exercise.title}</h4>
        <div className="buttons">
          <button onClick={performExerciseDeletion}>Delete</button>
          <Link to={`/exercises/${props.exercise.id}/edit`}>Edit</Link>
          <button onClick={performExerciseCompletion}>Toggle</button>
        </div>
      </div>
      <div className="details">
        <p>{props.exercise.details}</p>
      </div>
    </div>
  );
}

export default ExerciseItem;

components/ExerciseItem.css

.exercise {
  margin: 20px auto;
  background: white;
  padding: 10px 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  border-left: 10px solid var(--pink);
}
.exercise:hover {
  box-shadow: 0 16px 32px 0 rgba(0,0,0,0.9);
}
h3 {
  cursor: pointer;
}
.actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.exercise.complete {
  border-left: 10px solid var(--green);
}
.buttons {
  display:flex;
  flex-direction: column;
}
.buttons button,a {
 color: white;
  background: var(--pink);
  padding: 0.5rem;
  border: 0;
  border: 2px solid transparent;
  text-decoration: none;
  font-weight: 600;
  font-size:2rem;
  margin-bottom: 5px;
   border-radius: 6px;

}
.buttons button:hover, a:hover, button:active, a:active {
  background: rgb(225, 127, 143);
}
h4 {
  transform: skew(-21deg);
  background: var(--golden)
}

components/ExercisesList.css

.exercises-list {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  max-width: 600px;
  margin: 0 auto;
  color: #555;
}

components/ExercisesList.jsx

import React from 'react'
import ExerciseItem from './ExerciseItem';
import './ExercisesList.css'

function ExercisesList(props) {

  if (props.exercises.length === 0) return null;

  return (
    <div className="exercises-list">
      {props.exercises.map((exercise) => (
        <ExerciseItem
          key={exercise.id}
          exercise={exercise}
          onCompleteExercise={props.onCompleteExercise}
          onDeleteExercise={props.onDeleteExercise}
        />
      ))}
    </div>
  );

}

export default ExercisesList;

components/Navbar.css

.main-nav {
    text-align: center;
    margin: 40px auto;
  }
  .main-nav a{
    display: inline-block;
    text-decoration: none;
    margin: 0 10px;
    color: goldenrod;
    font-size: 20px;

  }
  .active-style {
    border-bottom: 2px solid goldenrod;
    padding-bottom: 4px;
  }

components/Navbar.jsx

import React from 'react'
import './Navbar.css';
import { NavLink } from "react-router-dom";

function Navbar() {
  return (
     <nav className="main-nav">
      <NavLink activeClassName="active-style" to="/home">
        Home
      </NavLink>
      <NavLink activeClassName="active-style" to="/create-exercise">
        Create Exercise
      </NavLink>
     </nav>
  );
}

export default Navbar

Pages (Views)

Create a folder for pages where we will house all our page components.

pages/HomePage.jsx

import React, { useState, useEffect  } from 'react';
import BaseFilter from '../components/BaseFilter';
import ExercisesList from '../components/ExercisesList';

const HomePage = () => {
  const [exercises, setExercises] = useState([]);
  const [currentFilter, setCurrentFilter] = useState('all');

  const updateFilterHandler = (newFilter) => {
    setCurrentFilter(newFilter);
  };

  const deleteExerciseHandler = function (id) {
    const patchedExercises = exercises.filter((exercise) => exercise.id !== id);
    setExercises(patchedExercises);
  };

  const completeExerciseHandler = function (id) {
    const clonedExercises = [...exercises];
    const currentExerciseIndex = clonedExercises.findIndex(
      (exercise) => exercise.id === id
    );
    const currentExercise = clonedExercises[currentExerciseIndex];
    currentExercise.complete = !currentExercise.complete;
    setExercises(clonedExercises);
  };


  useEffect(() => {
      try {
        const response = await fetch('http://localhost:3111/exercises');
        const fetchedExercises = await response.json();
        console.log(fetchedExercises);
        setExercises(fetchedExercises);

      } catch (error) {

        console.log(error);
      }
    }

    fetchExercises();

  }, []);


  let jsx = (
    <ExercisesList
      exercises={exercises}
      onCompleteExercise={completeExerciseHandler}
      onDeleteExercise={deleteExerciseHandler}
    />
  );
  if (currentFilter === 'completed') {
    jsx = (
      <ExercisesList
        exercises={exercises.filter((exercise) => exercise.complete)}
        onCompleteExercise={completeExerciseHandler}
        onDeleteExercise={deleteExerciseHandler}
      />
    );
  } else if (currentFilter === 'pending') {
    jsx = (
      <ExercisesList
        exercises={exercises.filter((exercise) => !exercise.complete)}
        onCompleteExercise={completeExerciseHandler}
        onDeleteExercise={deleteExerciseHandler}
      />
    );
  }
  return (
    <div>
      <BaseFilter 
        onUpdate={updateFilterHandler} 
        current={currentFilter} />
      {jsx}
    </div>
  );
};

export default HomePage;

pages/CreateExercise.css

form  {
    padding: 20px;
    border-radius: 10px;
    text-align: center;
  }
  label {
    display: block;
    color: goldenrod;
    text-transform: uppercase;
    font-size: 14px;
    font-weight: bold;
    letter-spacing: 1px;
    margin: 20px 0 10px 0
  }
  input {
    padding: 10px;
    width: 400px;
    max-width: 100%;
    box-sizing: border-box;
    border: 1px solid var(--grey);
  }
  textarea {
    padding: 10px;
    max-width: 100%;
    width: 400px;
    box-sizing: border-box;
    border: 1px solid var(--grey);

  }
  form button {
    display: block;
    margin: 20px auto;
    background: goldenrod;
    color: white;
    padding: 10px;
    border-radius: 6px;
    font-size: 16px;
    border: 2px solid transparent;
  }

pages/CreateExercise.jsx

import React, { useState } from 'react';
import './CreateExercise.css';
import { useHistory } from 'react-router-dom';

const CreateExercise = () => {

  const [exercise, setExercise] = useState({
    title: '',
    details: ''
  })

  const history = useHistory();

  const handleChange = event => {
    setExercise({
      ...exercise,
      [event.target.name] : event.target.value
    });
  }

  const handleExerciseCreation = (event) => {

    event.preventDefault();

    const newExercise = {
      title: exercise.title,
      details : exercise.details,
      complete: false,
      id: Math.floor(Math.random() * 10000),
    };

    console.log(newExercise);

    fetch('http://localhost:3111/exercises', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(newExercise)
    }).then(() => {
      history.push('/home');
    }).catch(err => console.log(err))
  };

  return (
    <form  onSubmit={handleExerciseCreation}>
      <label>Title</label>
      <input type="text" onChange={handleChange} name="title" value={exercise.title} maxLength="15" required />
      <label>Details</label>
      <textarea value={exercise.details} name="details"  onChange={handleChange} required></textarea>
      <button>Add Exercise</button>
    </form>
  );
};

export default CreateExercise;

pages/EditExercise.jsx

import React, { useState, useEffect } from 'react';
import './CreateExercise.css';
import { useHistory, useParams } from 'react-router-dom';

const EditExercise = () => {

  const [exercise, setExercise] = useState({
    title: '',
    details: '',
  });

  const params = useParams();
  const exerciseId = params.id;
  const history = useHistory();

  const handleChange = (event) => {
    setExercise({
      ...exercise,
      [event.target.name]: event.target.value,
    });
  };

  useEffect(() => {

    fetch(`http://localhost:3111/exercises/${exerciseId}`)
      .then((res) => res.json())
      .then((data) => {
         setExercise({
           title: data.title,
           details: data.details,
         });
      })
      .catch((err) => console.log(err));

  }, [exerciseId])

  const handleExerciseUpdation = (event) => {

     event.preventDefault();
     fetch(`http://localhost:3111/exercises/${exerciseId}`, {
       method: 'PATCH',
       headers: { 'Content-Type': 'application/json' },
       body: JSON.stringify(exercise),
     })
       .then(() => {
         history.push('/home');
       }).catch((err) => console.log(err));
  };

  return (
    <form onSubmit={handleExerciseUpdation}>
      <label>Title</label>
      <input
        type="text"
        onChange={handleChange}
        name="title"
        value={exercise.title}
        maxLength="15"
        required
      />
      <label>Details</label>
      <textarea
        value={exercise.details}
        name="details"
        onChange={handleChange}
        required
      ></textarea>
      <button>Update Exercise</button>
    </form>
  );
};

export default EditExercise;

So this is the code for our entire project.

PS – If you prefer learning React with a video. I do have a video on same where we create this exact project.

Check this :

Thanks for reading !

Categories
frontend javascript reactjs

When to use the useRef hook ?

Hey everyone 👋🏻,

In this article, let us learn about a very special React Hook called as the useRef hook and understand how and when to use it.

What is the useRef hook ?

useRef hook is something that I briefly discussed in one of my articles where I described useRef hook as something equivalent to

Removing the state updating function from the useState, so basically just extracting the piece of state and take away the ability of state updation. This is something that will be equivalent to the useRef hook. I also discussed in that article that both the ref and state values persists across renders, so it is not the case that on every subsequent re-render they get set back to some default. So do make a note of the above points.

useRef is a React Hook which accepts a single argument as the initial default value and gives us something called as a ref. A ref is kind of an object that has a property called as current.

Let us see an example :

function SomeComponent() { 

    const usernameRef = React.useRef(''); 
    const handleSomething = () => { 
       console.log(usernameRef.currrent); 
       usernameRef.current = someOtherValue; 
    }
}

Now the things to note here is that usernameRef.current is used to access the value of the ref and if we want to update the ref value, then we can simply do so by setting usernameRef.current to a value of our choice.

To know more about refs, check my existing article on useRef hook. Here is the link for the same :

Image description

https://dev.to/thenerdydev/useref-hook-useref-vs-usestate-3i7k

In the above article, I have also taken some examples where I have demonstrated the usage of the useRef hook, we have discussed :

1. Ref Example – 1 (An Interval Timer)
2. Ref Example – 2 (Working with DOM using refs)
3. The third thing that we discussed in that article was :

useRef just like useState persists a value across renders but unlike useState it does not trigger a re-render of the component.

So in essence,

useRef = useState – state updating function

If you don’t know about the useState, no worries. You can learn about the same in this article :

https://dev.to/thenerdydev/react-hooks-demystifying-the-usestate-hook-in-under-10-minutes-examples-video-29ab

Let’s sum up what we learnt :

A ref is a plain JavaScript Object
{ current: <some_value> }

If you want to create a ref with the current value as null, then you can also make use of the createRef method,
React.createRef()

This gives us :
{ current: null }

Next, useRef(someInitialValue) also gives us a ref { current: someInitialValue }. The interesting thing about useRef is that it memoizes this ref so that it stays persistent across multiple renders of the component.

Another point to make a note of is that :

useRef(null) is basically equivalent to useState(React.createRef())[0]
But this kind of abuses the functionality.

Lastly, we learnt that useState causes a re-render in contrast to useRef. The state and the ref values (both) persist across re-renders.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Categories
frontend javascript

5 Frontend Development Trends to follow in 2022

Hey everyone 👋🏻,

In this article, let us discuss about Top 5 Frontend Development Trends to follow in 2022

1. JavaScript

JavaScript is one of the most popular programming languages that you can learn these days. More than 70 percent of the websites are developed using JavaScript. It is continually evolving as more and more features are getting introduced into the language. JavaScript is the language that powers the web and is one of the top most tools that big companies are using these days.

There are currently 1.4 million JavaScript libraries that can be used by web developers across the world. In addition, web browsers now feature a separate JavaScript engine that speeds up these computations, resulting in faster page load times. JavaScript is a constant trend in front end development with a plethora of libraries.

Image description
Source

2. JAM Stack

JAM Stack is not a technology or language but an architectural design that uses JavaScript, APIs, and Markup. These individual technologies can be combined to produce a decoupled web application whose front-end and back-end are separated. JAM Stack boasts of providing following benefits to websites and project workflows : Security, Scale, Performance, Maintenance, Portability and Developer Experience

Image description
Check the website : https://jamstack.org

3. Micro-frontends

Image description

The term Micro Frontends first came up in ThoughtWorks Technology Radar at the end of 2016. It extends the concepts of micro services to the frontend world. The current trend is to build a feature-rich and powerful browser application, aka single page app, which sits on top of a micro service architecture. Over time the frontend layer, often developed by a separate team, grows and gets more difficult to maintain. That’s what we call a Frontend Monolith.

The idea behind Micro Frontends is to think about a website or web app as a composition of features which are owned by independent teams. Each team has a distinct area of business or mission it cares about and specialises in. A team is cross functional and develops its features end-to-end, from database to user interface.

Source

4. React.js

Image description

React.js is one of the most popular JavaScript libraries for building modern and sleek user interfaces these days. It does not need an introduction as such because it is that popular that almost every new developer these days is learning React. React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.

Image description
Source : https://www.npmtrends.com/react-vs-vue-vs-@angular/core

5. Progressive Web Applications

Image description

The idea behind Progressive Web Applications is to provide a native app experience to the user through the browser itself. PWAs are extremely beneficial as they are of lesser size (in KBs) and provide a near-similar experience like a native application. You would often see PWAs are released as “Lite” versions on the play store and do not exceed 1 MB in size. Even though it looks like a native app, it opens up a browser inside to view the items.

Progressive Web Apps (PWAs) are web apps that use service workers, manifests, and other web-platform features in combination with progressive enhancement to give users an experience on par with native apps.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text
Categories
frontend javascript vuejs

✨8 Vue Projects Every Beginner Should Try

Hey everyone 👋🏻,

In this article, let us see 8 Vue Projects Every Beginner Should Try.

This article was first published on https://the-nerdy-dev.com/.
Check the website for more interesting articles and tutorials on Web Development.

Introduction

Image description

Vue.js is an open-source model–view–view-model (MVVM) front end JavaScript framework for building user interfaces and single-page applications. It was created by Evan You, and is maintained by him and the rest of the active core team members

1. 6 Hours Vue.js and Firebase Project – FireBlogs by @traversymedia

Learn how to build a multi-user blog project with Vue.js, Vuex and Firebase.

What will you learn?

  1. Vue.js basics and fundmentals
  2. State Management using Vuex
  3. Working with Firebase

2. Build a COVID Tracker App with Vue.js and Tailwind

In this project, Brad uses Vue.js and Tailwind to create a Simple COVID Tracker Application.

What will you learn?

  1. Vue.js Fundamentals and Basics
  2. Working with Tailwind.css

3. Vue.js + Vuetify + Firebase Project – DevMeetup

In this tutorial, Maximilian Schwarzmuller shows how to build a complete Project – a Developer Meetup App – with Vue.js 2, Vuetify and Firebase. This is a 24 part series.

Image description

www.youtube.com/playlist?list=PL55RiY5tL51qxUbODJG9cgrsVd7ZHbPrt

What will you learn?

  1. Vue.js 2 Fundamentals and Basics
  2. Vuetify Components
  3. Working with Firebase

4. Build a Weather App in VueJS | Vue Beginner Tutorial

Learn how to make a Weather app in Vue JS, we use the Open Weather Map API to make calls to a restful api to return the current weather data. This uses the Modern Javascript Fetch API along with Vue JS Methods and conditionals.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Interacting with APIs via API calls.

5. Build a Invoice App With Vue 3, Vuex & Firebase

In this video, we build out a full CRUD (create, read, update & delete) invoice app using Vue 3, Vuex & Firebase.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Working with Firebase
  3. State Management using Vuex

6. Create a Gridsome Portfolio – Vue.js project

Learn how to make a portfolio kind of an application using Gridsome library with Vue.js

What will you learn?

  1. Vue.js basics and fundamentals
  2. Gridsome library

7. E-commerce Website With Django and Vue Tutorial (Django Rest Framework)

Learn how to build an e-commerce website using Django and Vue from scratch. Django uses Python Vue uses JavaScript.

Django Rest Framework is used to build the API and backend.
The frontend is a separate Vue project. To handle the payments, we implement Stripe.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Learn Django to create a full stack application

8. Full Stack Web App in Vue.js & Express.js

Image description
Learn how to build a full stack application using Vue.js and Express.js with Postgres as the database

What will you learn?

  1. Vue basics and fundamentals
  2. Making a full stack application with Vue.js and Express along with Postgres as the database

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev
👉🏻 Join our Discord Server : https://discord.gg/fgbtN2a

Categories
css frontend html web development

Web Dev Made Easy

Hey everyone 👋🏻,

In this article, I will tell you about a website using which you can use as a resource for learning Web Development.

So the website name is this :

web.dev

https://web.dev

Image description

Now some of the featured courses on their website are :

Image description

1. Learn Responsive Design

Image description

This course takes you on a journey through the many facets of modern responsive web design. The first few modules will ease you in with a history of where responsive design came from and a look at the fundamentals of responsive layouts. From there, you’ll learn about responsive images, typography, accessibility and more.

Along the way you’ll find out how to make websites responsive to user preferences and device capabilities. By the end, you’ll also have an understanding of what the future might hold for responsive design.

Each module has demos and self-assessments for you to test your knowledge.

This course is created for beginner and intermediate designers and developers. A basic understanding of HTML and CSS should be enough. You don’t need to know any JavaScript. If you’re completely new to making websites, there’s an introduction to HTML and another course to help you learn CSS.

2. Learn Forms

Image description

This course breaks down HTML forms into easy to understand pieces. Over the next few modules, you’ll learn how an HTML form works and how to use them effectively in your projects. Use the menu pane by the Learn Forms logo to navigate the modules.

You’ll learn how to build a basic HTML form, about HTML form elements, styling forms, help users re-entering data, ensuring the form is accessible, and secure, how to test your forms, and about specific form types.

Each module is full of interactive demos and self-assessments for you to test your knowledge.

This course is suitable for beginners and advanced HTML developers. The first few modules help you get started with building HTML forms, the other modules give more detail. You can go through the series from start to finish to get a general understanding of HTML forms, or pick a specific module you want to learn more about.

3. Learn Progressive Web Apps

Image description

This course covers the fundamentals of Progressive Web App development into easy-to-understand pieces. Over the following modules, you’ll learn what a Progressive Web App is, how to create one or upgrade your existing web content, and how to add all the pieces for an offline, installable app. Use the menu pane by the “Learn PWA” logo to navigate the modules.

You’ll learn PWA fundamentals like the Web App Manifest, Service Workers, how to design with an app in mind, what’s different from a classic web app, how to use other tools to test and debug your PWA. After these fundamentals, you’ll learn about integration with the platform and operating system, how to enhance your PWA’s installation and usage experience, and how to offer an offline experience.

Each module includes interactive demos and self-assessments for you to test your knowledge. You will be able to test and try demos on your mobile phone, tablet, or laptop while playing with the code to understand the fundamentals of what makes a Progressive Web App.

This course is created for a beginner and advanced web developers alike. You can go through the series from start to finish to get a general understanding of PWA from top to bottom, or you can use it as a reference for specific subjects. For those new to web development you will need a grounding in HTML, CSS, and JavaScript to follow along. Check out Learn CSS, and the HTML and JavaScript courses on MDN.

4. Learn CSS

Image description

This course breaks down the fundamentals of CSS into digestible, easy to understand pieces. Over the next few modules, you’ll learn how the core aspects of CSS work and how to use them effectively in your projects. Use the menu pane by the “Learn CSS” logo to navigate the modules.

You’ll learn CSS fundamentals like the box model, cascade and specificity, flexbox, grid and z-index. And, along with these fundamentals, you’ll learn about functions, color types, gradients, logical properties and inheritance to make you a well-rounded front-end developer, ready to take on any user interface.

Each module is full of interactive demos and self-assessments for you to test your knowledge. In addition to learning through reading and demos, there is an accompanying podcast episode for each topic as another way to learn and continue expanding your knowledge.

This course is created for beginner and advanced CSS developers alike. You can go through the series from start to finish to get a general understanding of CSS from top to bottom, or you can use it as a reference for specific styling subjects. For those new to web development overall, check out the intro to HTML course from MDN to learn all about how to write markup and link your stylesheets.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text