Popular use cases

How to use state with hooks in React

Last updated Jan 23, 2020
import React, { useState } from "react";

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

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <>
      <h1>{count} times</h1>
      <button onClick={handleClick}>Add 1</button>
    </>
  );
}

How to check if element has class in JavaScript

Last updated Aug 24, 2018
<div id="box" class="active"></div>
const element = document.querySelector("#box");

element.classList.contains("active");
true

How to interpolate in JavaScript

Last updated Nov 11, 2017
const name = "John";

console.log(`Welcome ${name}.
You have ${2 * 5} new notifications!`);
Welcome John.
You have 10 new notifications!

How to add class to element in JavaScript

Last updated Nov 11, 2017
<div id="box"></div>
const element = document.querySelector("#box");

element.classList.add("class-name");

How to replace spaces with dashes in JavaScript

Last updated Nov 11, 2017
const text = "codetogo saved me tons of time";

text.replace(/ /g, "-");
codetogo-saved-me-tons-of-time

How to reload page in JavaScript

Last updated Nov 11, 2017
window.location.reload();

How to find element by id in JavaScript

Last updated Nov 11, 2017
<div id="box"></div>
const element = document.querySelector("#box");

How to loop through array in JavaScript

Last updated Nov 11, 2017
const people = ["Sam", "Alex", "Charlie"];

people.forEach(person => {
  console.log(person);
});
Sam
Alex
Charlie

How to listen to click event in JavaScript

Last updated Nov 11, 2017
<div id="box"></div>
const element = document.querySelector("#box");

element.addEventListener("click", event => {
  console.log("Element clicked");
});

How to get keys of object in JavaScript

Last updated Nov 11, 2017
const person = {
  key: "value",
  first_name: "John",
  last_name: "Doe"
};

Object.keys(person);
['key', 'first_name', 'last_name']

How to increment a variable in JavaScript

Last updated Nov 11, 2017
let counter = 0;
counter++;
1

How to uppercase a string in JavaScript

Last updated Nov 11, 2017
const text = "Hello World";

text.toUpperCase();
HELLO WORLD