Categories
JavaScript jQuery

jQuery to Vanilla JavaScript Transition Cheat Sheet — Basic Operations

Vanilla JavaScript in the browser now has many of the features of jQuery built in,

Therefore, we don’t need to use jQuery to do many things.

In this article, we’ll look at the vanilla JavaScript equivalent of jQuery features.

Selecting Elements

We can use the querySelector method to select a single element with the given selector in vanilla JavaScript.

Vanilla JavaScript also has the querySelectorAll method to select multiple elements with the given selector with vanilla JavaScript.

For instance, we can write:

document.querySelector("div");

to select the first div in the document.

And select all the divs with:

document.querySelectorAll("div");

querySelectorAll returns a NodeList object, which is an iterable object with all the selected nodes inside.

In jQuery, we have:

$("div");

to select all the divs.

Run a Function on All Selected Elements

In jQuery, we can run a function on all selected elements.

For instance, we can hide all the divs by writing:

$("div").hide();

To do the same thing with vanilla JavaScript, we can use the forEach method:

document.querySelectorAll("div")
  .forEach(div => {
    div.style.display = "none"
  })

We can also use the for-of loop:

for (const div of document.querySelectorAll("div")) {
  div.style.display = "none"
}

The NodeList returned by querySelector can also be spread:

const divs = [...document.querySelectorAll("div")]
divs
  .forEach(div => {
    div.style.display = "none"
  })

divs is now an array instead of a NodeList.

This means we can run many array methods on it.

Finding an Element within Another

To find an element within another with jQuery, we use the find method:

const div = $("div");
//...
div.find(".box");

To do the same thing with vanilla JavaScript, we can use querySelector to find one element and querySelectorAll to find all instances of the element with the given selector.

So we write:

const div = document.querySelector('div')
//...
div.querySelector(".box");

to find the first element with class box in the div.

And we write:

const div = document.querySelector('div')
//...
div.querySelectorAll(".box");

to find all elements with class box in the div.

Traversing the Tree with parent(), next(), and prev()

jQuery has the parent method to get the parent element of an element.

jQuery’s next method returns the next sibling element of an element.

And jQuery’s prev method returns the previous sibling element of an element.

To use them, we can write:

$("div").next();
$("div").prev();
$("div").parent();

In vanilla JavaScript, we can write:

const div = document.querySelector("div");
div.nextElementSibling;
div.previousElementSibling;
div.parentElement;

nextElementSibling returns the next sibling element.

previousElementSibling returns the previous sibling element.

And parentElement returns the parent element.

Working with Events

jQuery lets us add event handlers easily to an element.

For instance, we can write:

$("button").click((e) => {
  /* handle click event */
});
$("button").mouseenter((e) => {
  /* handle click event */
});
$(document).keyup((e) => {
  /* handle key up event */
});

to add a click event handler, mouseenter event handler, and keyup event handler on the element that’s selected respectively.

To do the same thing with vanilla JavaScript, we can use the addEventListener method:

document
  .querySelector("button")
  .addEventListener("click", (e) => {
    /* ... */
  });

document
  .querySelector("button")
  .addEventListener("mouseenter", (e) => {
    /* ... */
  });

document
  .addEventListener("keyup", (e) => {
    /* ... */
  });

We just select the element with querySelector and call addEventListener with the event name as the first argument and the event handler callback as the 2nd argument.

Conclusion

We can do many basic DOM operations like selecting elements, traversing the DOM tree, and adding event listeners to elements with vanilla JavaScript.

Categories
React

Update React Query Cache with the setQueryData Method

Sometimes, we may want to update the React Query cache so that the data that’s used to render the HTML is updated on the client-side to display the latest data without fetching it from the server again.

In this article, we’ll look at how to use React Query’s setQueryData method to update the query cache data on the client-side.

Using the setQueryData Method to Update Data Cached from Making Requests

We can use the React Query’s queryClient ‘s setQueryData method to update the cached response data from making HTTP requests.

To do this, we write:

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider } from "react-query";

import App from "./App";
export const queryClient = new QueryClient();

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </StrictMode>,
  rootElement
);

App.js

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";
import { queryClient } from "./index";

export default function App() {
  const { data } = useQuery("yesno", () => axios.get("https://yesno.wtf/api"));

const setData = () => {
    queryClient.setQueryData("yesno", (data) => {
      return {
        data: {
          ...data.data,
          answer: data.data.answer === "yes" ? "no" : "yes"
        }
      };
    });
  };

  return (
    <div>
      <button onClick={setData}>toggle</button>
      <div>{data?.data?.answer}</div>
    </div>
  );
}

In index.js , we create a new QueryClient instance that we use with the QueryClientProvider component so that we can use the React Query hooks to make requests.

Then in App.js , we use the useQuery hook to make requests.

We pass in the name of the query as the first argument.

The 2nd argument is a function that returns a promise with the HTTP request response.

The data property of the returned object has the response data.

In the setData function, we call queryClient.setQueryData with the identifier of the request we want to update as passed into useQuery ‘s first argument.

The 2nd argument is a callback that takes the cached response data for the request with the identifier in the first argument, and we return the object that will be the new value of the item that’s cached with the given identifier.

We toggle the value of the data.data.answer value from the response in setData .

And we call that when we click on the toggle button.

Therefore, we should see the data.data.answer value toggle between 'yes' and 'no' when we click the toggle button.

This is because we update the query cache data entry for the request with the identifier passed into the first argument of sertQueryData to what we want on the client-side.

Conclusion

We can update the cached response data on the client side with React Query’s query client’s setQueryData method.

Categories
Chakra UI Vue

UI Development with Chakra UI Vue — Statistics Display

Chakra UI Vue is a UI framework made for Vue.js that lets us add good-looking UI components into our Vue app.

This article will look at how to get started with UI development with Chakra UI Vue.

Statistics Component

Chakra UI Vue comes with a component to display statistics.

To use it, we write:

<template>
  <c-box>
    <c-stat>
      <c-stat-label>Collected Fees</c-stat-label>
      <c-stat-number>$500.00</c-stat-number>
      <c-stat-helper-text>Jan 12 - Jan 28</c-stat-helper-text>
    </c-stat>
  </c-box>
</template>

<script>
import { CBox, CStat, CStatLabel, CStatNumber } from "@chakra-ui/vue";

export default {
  components: {
    CBox,
    CStat,
    CStatLabel,
    CStatNumber,
  },
};
</script>

We add the c-stat component to add the statistics container.

c-stat-label is the label for the statistic.

c-stat-number is the container for the statistic number.

c-stat-helper-text is the container for the helper text.

We can add a group of statistics with the c-stat-group component:

<template>
  <c-box>
    <c-stat-group>
      <c-stat>
        <c-stat-label>Sent</c-stat-label>
        <c-stat-number>676585</c-stat-number>
        <c-stat-helper-text>
          <c-stat-arrow type="increase" />
          30.60%
        </c-stat-helper-text>
      </c-stat>
      <c-stat>
        <c-stat-label>Clicked</c-stat-label>
        <c-stat-number>45</c-stat-number>
        <c-stat-helper-text>
          <c-stat-arrow type="decrease" />
          -5.20%
        </c-stat-helper-text>
      </c-stat>
    </c-stat-group>
  </c-box>
</template>

<script>
import {
  CBox,
  CStat,
  CStatLabel,
  CStatNumber,
  CStatHelpText,
  CStatArrow,
  CStatGroup,
} from "@chakra-ui/vue";

export default {
  components: {
    CBox,
    CStat,
    CStatLabel,
    CStatNumber,
    CStatHelpText,
    CStatArrow,
    CStatGroup,
  },
};
</script>

We wrap c-stat-group from multiple c-stat components.

Also, we add the c-stat-arrow component to add arrows for increases and increases, which are set by the type prop.

Conclusion

We can a statistic display with Chakra UI Vue.

Categories
Chakra UI Vue

UI Development with Chakra UI Vue — Loading Spinner

Chakra UI Vue is a UI framework made for Vue.js that lets us add good-looking UI components into our Vue app.

This article will look at how to get started with UI development with Chakra UI Vue.

Loading Spinner

We can add a loading spinner into our Vue app with Chakra UI Vue.

To add it, we write:

<template>
  <c-box>
    <c-spinner />
  </c-box>
</template>

<script>
import { CBox, CSpinner } from "@chakra-ui/vue";

export default {
  components: {
    CBox,
    CSpinner,
  },
};
</script>

We add the c-spinner component to display the spinner.

We can change the color of the spinner with the color prop:

<template>
  <c-box>
    <c-spinner color="blue.500" />
  </c-box>
</template>

<script>
import { CBox, CSpinner } from "@chakra-ui/vue";

export default {
  components: {
    CBox,
    CSpinner,
  },
};
</script>

And we can change the size of it with the size prop:

<template>
  <c-box>
    <c-spinner size="lg" />
  </c-box>
</template>

<script>
import { CBox, CSpinner } from "@chakra-ui/vue";

export default {
  components: {
    CBox,
    CSpinner,
  },
};
</script>

lg is large. We can also set it to xs for extra small, sm for small, md for medium or xl for extra-large.

Other options we can change include the thickness, speed of the spinning, and the color of the empty area.

To change them, we write:

<template>
  <c-box>
    <c-spinner
      thickness="4px"
      speed="0.65s"
      empty-color="green.200"
      color="vue.500"
    />
  </c-box>
</template>

<script>
import { CBox, CSpinner } from "@chakra-ui/vue";

export default {
  components: {
    CBox,
    CSpinner,
  },
};
</script>

thickness changes the thickness of the spinner ring.

speed changes the time it takes to complete one rotation cycle.

empty-color sets the color of the empty part of the spinner ring.

Conclusion

We can add a loading spinner into our Vue app with Chakra UI Vue.

Categories
Chakra UI Vue

UI Development with Chakra UI Vue — Select Dropdowns

Chakra UI Vue is a UI framework made for Vue.js that lets us add good-looking UI components into our Vue app.

This article will look at how to get started with UI development with Chakra UI Vue.

Select

Chakra UI Vue comes with a styled select dropdown component.

To add it, we write:

<template>
  <c-box>
    <c-select v-model="fruit" placeholder="Select Fruit">
      <option value="apple">apple</option>
      <option value="orange">orange</option>
      <option value="grape">grape</option>
    </c-select>
  </c-box>
</template>

<script>
import { CBox, CSelect } from "@chakra-ui/vue";

export default {
  components: {
    CBox,
    CSelect,
  },
  data() {
    return {
      fruit: "",
    };
  },
};
</script>

We add the c-select component with v-model to bind the selected value to the fruit reactive property.

The value attribute value of the chosen option will be set as the value of fruit .

placeholder sets the placeholder.

And we add the options with the option tag.

We can set the style variant of the dropdown.

To do this, we just have to set the variant prop:

<template>
  <c-box>
    <c-select variant="filled" v-model="fruit" placeholder="Select Fruit">
      <option value="apple">apple</option>
      <option value="orange">orange</option>
      <option value="grape">grape</option>
    </c-select>
  </c-box>
</template>

<script>
import { CBox, CSelect } from "@chakra-ui/vue";

export default {
  components: {
    CBox,
    CSelect,
  },
  data() {
    return {
      fruit: "",
    };
  },
};
</script>

filled will fill the background with a color.

We can also set it to outline, flushed, or unstyled .

outline adds an outline around the dropdown.

flushed removes the outline.

unstyled means no styles are added to the dropdown.

We can also set the styles of the dropdown ourselves.

To do this, we write:

<template>
  <c-box>
    <c-select
      backgroundColor="tomato"
      borderColor="tomato"
      color="white"
      v-model="fruit"
      placeholder="Select Fruit"
    >
      <option value="apple">apple</option>
      <option value="orange">orange</option>
      <option value="grape">grape</option>
    </c-select>
  </c-box>
</template>

<script>
import { CBox, CSelect } from "@chakra-ui/vue";

export default {
  components: {
    CBox,
    CSelect,
  },
  data() {
    return {
      fruit: "",
    };
  },
};
</script>

backgroundColor sets the background color. borderColor sets the border color. And color sets the text color.

Conclusion

We can add a dropdown easily with Chakra UI Vue.