Snippets Collections
import React, { useEffect, useState } from "react";
import { DownArrowIcon } from "./Icons";

const BackToTop = () => {
  const [scrollPosition, setScrollPosition] = useState(0);

  // SCROLL TO TOP FUNCTION WHEN CLICK ON THIS PAGE SCROLL TOP
  function scrollToTop() {
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  }

  // TO FIND SCROLL Y POSITION
  const handleScroll = () => {
    const position = window.pageYOffset;
    setScrollPosition(position);
  };

  // THIS USEFFECT GIVE US POSITION OF SCROLL IN EVERY PIXELS WE SCROLL
  useEffect(() => {
    window.addEventListener("scroll", handleScroll, { passive: true });

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  return (
    <>
      {/* // IF PAGE SCROLL VALUE GRATER THAN 500 THEN SHOW BACK TO TOP BUTTON */}
      {scrollPosition > 300 && (
        <div className="back-to-top " onClick={() => scrollToTop()}>
          <DownArrowIcon />
        </div>
      )}
    </>
  );
};

export default BackToTop;


export const DownArrowIcon = () => {
  return (
    <>
      <svg
        width="25"
        height="10"
        viewBox="0 0 28 16"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path d="M1 1L14 14L27 1" stroke="#1EADB6" strokeWidth="5" />
      </svg>
    </>
  );
};


// BACKTOP TOP STYLE ADD IN CSS FILE

// .back-to-top {
//   position: fixed;
//   bottom: 20px;
//   right: 20px;
//   z-index: 999;
//   background: #18c7f4;
//   border-radius: 50%;
//   width: 45px;
//   height: 45px;
//   display: -webkit-box;
//   display: -ms-flexbox;
//   display: flex;
//   -webkit-box-pack: center;
//   -ms-flex-pack: center;
//   justify-content: center;
//   -webkit-box-align: center;
//   -ms-flex-align: center;
//   align-items: center;
//   cursor: pointer;
//   -webkit-transition: all 0.3s ease-in-out;
//   -o-transition: all 0.3s ease-in-out;
//   transition: all 0.3s ease-in-out;
//   -webkit-animation: updown-element-animation 2s infinite;
//   animation: updown-element-animation 2s infinite;
// }


 const initialState = {
    name: "",
    email: "",
    mobile: "",
    subject: "",
    message: "",
  };
  const [formData, setFormData] = useState(initialState);

  const newsletterHandler = (e) => {
    e.preventDefault();
    console.log(formData);
    window.location.href =
      "mailto:info@gmail.com?" +
      "&body=" +
      "Name : " +
      formData.name +
      "%0D" +
      "Email : " +
      formData.email +
      "%0D" +
      "Mobile : " +
      formData.mobile +
      "%0D" +
      "Subject : " +
      formData.subject +
      "%0D" +
      "Message : " +
      formData.message;

    setTimeout(() => {
      setFormData(initialState);
    }, 3000);
  };
   <form onSubmit={newsletterHandler} className="w-100">
                <div className="d-flex flex-column flex-lg-row justify-content-between w-100">
                  <div className=" pe-lg-5 w-100">
                    <label className="font-xsm w-100">
                      Name <br />
                      <input
                        onChange={(e) =>
                          setFormData({ ...formData, name: e.target.value })
                        }
                        value={formData.name}
                        className="w-100"
                        type="text"
                        name="Name"
                      />
                    </label>
                  </div>
                  <div className="mt-3 mt-lg-0 w-100">
                    <label className="font-xsm w-100">
                      Email <br />
                      <input
                        onChange={(e) =>
                          setFormData({ ...formData, email: e.target.value })
                        }
                        value={formData.email}
                        className="w-100"
                        type="email"
                        name="Email"
                      />
                    </label>
                  </div>
                </div>
                <div className="d-flex flex-column flex-lg-row justify-content-between mt-3 mt-lg-4 pt-lg-2">
                  <div className="pe-lg-5 w-100">
                    <label className="font-xsm w-100">
                      Mobile <br />
                      <input
                        onChange={(e) =>
                          setFormData({ ...formData, mobile: e.target.value })
                        }
                        value={formData.mobile}
                        className="w-100"
                        type="Number"
                        name="Mobile"
                      />
                    </label>
                  </div>
                  <div className="mt-3 mt-lg-0 w-100">
                    <label className="font-xsm w-100">
                      Your Subject <br />
                      <input
                        onChange={(e) =>
                          setFormData({ ...formData, subject: e.target.value })
                        }
                        value={formData.subject}
                        className="w-100"
                        type="text"
                        name="Your Subject"
                      />
                    </label>
                  </div>
                </div>
                <label className="font-xsm w-100 color-blue mt-4 pt-lg-2">
                  Message
                  <textarea
                    onChange={(e) =>
                      setFormData({ ...formData, message: e.target.value })
                    }
                    value={formData.message}
                    className="w-100  mt-2 mb-2 "
                    rows={5}
                    type="text"
                    name="Message"
                    placeholder="Type your message here "
                  ></textarea>
                </label>

                <button
                  type="submit"
                  className="font-normal fw-bold mt-4 color-white mb-2 mb-lg-0"
                >
                  Send Message
                </button>
              </form>
const groupData = (array, key) => {
      return array.reduce((acc, curr) => {
        const group = curr[key];
        if (!acc[group]) {
          acc[group] = [];
        }
        acc[group].push(curr);
        return acc;
      });
    };
    const groupedData = groupData(galleryData, "building");
//!Trickiest of all array methods

const arr = [1,2,3,4,5]
//undefined

//Array method for two goals:
//1. end up with one value in the end
//2. persist the return or the outcome of iterating over our elements in each subsequent iteration

//reduce() takes two arguments

//So in the first run, accumulator = 0
//Second argument ("0") means we start with the value 0

arr.reduce((accumulator, currentElement) =>
accumulator + currentElement, 0)
//15 

//How this function works:
//first run: accu = 0 + cV 1 

//second run: accu = 1 + cv 2

//third run: accu = 3 + cv 3

//fourth run: accu = 6 + cv 4

//fifth run: accu = 10 + cv 5 

// --> 15 (end result)


//if we choose as second argument 10 instead of 0
//then the accumulator starts at 10
//The find() method returns the value of the element of an array
//that FIRST fulfils the condition of a provided test function. Otherwise, undefined is returned.


const arr = [1,3,5,7,9]
//undefined

arr.find(el => el ===5)
//5

arr.find(el => el > 4)
//5

const peopleArray = [{id:1}, {id:4}, {id:7}]
//undefined

peopleArray.find(persom => person.id ===4)
//{id:4}
//Checks whether element exists in array

const myArray = [2,3,4,5,6]

myArray.includes(2)
//true
myArray.includes(8)
//false

const newArra = [{id:1}, {id:2}, {id:3}]
//undefined

//first argument: searched number, second argument: index
//so: is at index 3 the number 2?
myArray.includes(2,3)
//false
const myArray = [2,4,5,6,9]

my.Array.filter(el => el < 5)

//keeps anything in new array that returns true
// [2,4]

//but it does not mutate the array, so
myArray
// remains  [2,4,5,6,9]
// Leave the next line, the form must be assigned to a variable named 'form' in order for the exercise test to pass
const form = document.querySelector('form');
const product = document.querySelector("#product");
const qty = document.querySelector("#qty");

const groceryList = document.querySelector('#list');

form.addEventListener("submit", function(evt){
    evt.preventDefault();
    const newLI = document.createElement("LI");
  //innerHTML or innerText or textContent
    newLI.innerHTML = `${product.value}${qty.value}`
    groceryList.appendChild(newLI);
    product.value = ""
    qty.value = ""

});
 WRITE YOUR CODE IN HERE:
    for (let i = 0; i < 100; i++) {
        const newButton = document.createElement('button');
        newButton.innerText = 'Hey!';
        container.appendChild(newButton);
     
    }
//To convert each background given to a second value

const newBackgrounds = document.querySelectorAll('li');
for(let li of newBackgrounds){
    li.classList.toggle('highlight');
} 
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
//for...of - loop
const spans = document.querySelectorAll("span");
let count = 0
for (let span of spans){
    span.style.color = colors[count]
    count++
}
//alternative:
//for-loop
const spans = document.querySelectorAll('span'); 
for(let i =0; i< colors.length; i++){
    spans[i].style.color = colors[i];
} 

//Turning a right floating and squared image in a centered text and a round image
const sth = document.querySelector("#container")
sth.style.textAlign = "center"
sth.querySelector("img").style.width = "150px";
sth.querySelector("img").style.borderRadius = "50%";
//innerText
//gives the plain text and thus, removes all other elements in that paragraph
document.querySelector("p").innerText

//textContent
//gives the text with spacing taking into account the original mark up of the text
//return every element
document.querySelector("p").textContent

//innerHTML
//gives the text + markups
document.querySelector("p").innerHTML


//Manipulating 
//with innerText
document.querySelector("p").innerHTML = "<i>Something!</i>"
// <i>Something!</i> 

//with innerHTML
document.querySelector("p").innerHTML = "<i>Something!</i>"
// Something! (in italic)


//reference classes with (".X), ids ("#X"), tages ("tagname")(like "h1") and types ("input[type='checkbox']")

const doneTodos = document.querySelectorAll(".done");
const checkbox = document.querySelector("input[type='checkbox']");

//All links in paragraphs
const links = document.querySelectorAll("p a")
let square = {
    area(side){return side * side},
    perimeter(side){return side * 4  }
    };
    
//short for
let square = {
  area: function (side){
    return side * side
  },
  perimeter: function (side){
    return side *4
  }
}
// DEFINE YOUR FUNCTION BELOW:
    function returnDay(num){
        const days = [null,'Monday',"Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
        
      if(num >0 && num <8){
            return days[num]
        }else return null
    }

//using ternary operator
    function returnDay(num){
        const days = [null,'Monday',"Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
        return num> 0 && num < 8 ?days[num] : null;
    }
// DEFINE YOUR FUNCTION BELOW:
// This function should return the sum of all the numebrs in the array
function sumArray(arr){
    let sum = 0
    for (let i = 0; i < arr.length; i++){
        sum += arr[i]
    }
    return sum
// DEFINE YOUR FUNCTION BELOW:
//str.slice(1) = alles was ab(!) index 1 folgt

function capitalize(str){
  const str2 = str.charAt(0).toUpperCase() + str.slice(1);
   return str2
}
capitalize("eggplant")
capitalize("pamplemouse")
capitalize("squid")
// DEFINE YOUR FUNCTION BELOW:
function lastElement(arr){
    if (arr.length === 0 ){
    return null
      
             //to get the wanted arr's index number
}else return arr[arr.length-1]
}

lastElement([3,5,7])
lastElement([1])
lastElement([0])
//How functions work with parameters
//Order of paramters matters

function repeat(str, numTimes){
  let result = "";
  for (let i = 0; i < numTimes; i++)
    results += str;
}

console.log(result)
repeat("Good",5)
//Good Good Good Good Good
// This example shows three ways to create a new array from the existing fruits array: first by using spread syntax, then by using the from() method, and then by using the slice() method.

const fruits = ['Strawberry', 'Mango'];

// Create a copy using spread syntax.
const fruitsCopy = [...fruits];
// ["Strawberry", "Mango"]

// Create a copy using the from() method.
const fruitsCopy = Array.from(fruits);
// ["Strawberry", "Mango"]

// Create a copy using the slice() method.
const fruitsCopy = fruits.slice();
// ["Strawberry", "Mango"]
function filteredArray(arr, elem) {
  let newArr = [];
  // Only change code below this line
  // arr.length = 4

for(let i = 0; i < arr.length; i += 1){

//["flutes", 4] ()=== arr[1])--> 2 is not showing up ...i dont understand????

if(arr[i].indexOf(elem) === -1){
newArr.push(arr[i]);
}
}
  // Only change code above this line
  return newArr;
}

console.log(filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2));
//Remember that, for the inner loop, we need to check the .length of arr[i] since arr[i] is one of the sub-arrays we looked at earlier.

function multiplyAll(arr) {
  let product = 1;
  // Only change code below this line

  //Outer Loop
  for (let i = 0; i < arr.length; i++){
  //Inner Loop
    
  for (let j = 0; j < arr[i].length; j++){
    
  //Finally, multiply product by every element in each of the sub-arrays: 
  product *= arr[i][j]
  }
  }
  // Only change code above this line
  console.log(product)
  return product;
}

multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);


//Closer look
//The overall view:
//Sub-array 0: 1,2
//Element 0: 1
//Element 1: 2
//Sub-array 1: 3,4
//Element 0: 3
//Element 1: 4
//Sub-array 2: 5,6,7
//Element 0: 5
//Element 1: 6
//Element 2: 7


//The first iteration of i grabs the first sub-array, [1, 2]. Then the first iteration of j goes through each element in that sub-array

// i is 0
arr[0] // [1, 2];

// j is 0
arr[0][0] // 1
// j is 1
arr[0][1] // 2

-----

// i is 1
arr[1] // [3, 4]

// j is 0
arr[1][0] // 3
// j is 1
arr[1][1] // 4

...


//To better understand arr[i][j] we can replace "arr[i]"" by "subarray"
function multiplyAll(arr) {
  let product = 1;
  // Only change code below this line
  for (let i = 0; i < arr.length; i++) {
    const subArray = arr[i];
    for (let j = 0; j < subArray.length; j++) {
      product *= subArray[j];
    }
  }
  // Only change code above this line
  return product;
}

multiplyAll([[1,2],[3,4],[5,6,7]]);

const myArr = [2, 3, 4, 5, 6];
let total = 0

for(let i = 0; i < myArr.length; i++){
  total += myArr[i]
}

//Mind: dont use ".length-1" because ???
//		dont use "push" as we don't add numbers to an array, but add each value accumulating 		 to a the variable "total"
Simulate a Max Method on Arrays


Math.max(1,2,3);  // Will return 3 
import axios from "axios";
import { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  //  let arr = [A, B, C];

  const [item, setItem] = useState([]);

  useEffect(() => {
    axios.get("https://swapi.dev/api/planets/?page=2").then((item) => {
      console.log(item);
      setItem(item.data.results);
    });
  }, []);

  return (
    <div className="App">
      <ul>
        {item.map((planet) => {
          return <li>{planet.name}</li>;
        })}
      </ul>
    </div>
  );
}
//Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false.

function boolToWord( bool ){
const str = bool === true ? "Yes" : "No"
return str
  }
//Build a function that returns an array of integers from n to 1 where n>0.Example : n=5 --> [5,4,3,2,1]


const reverseSeq = n => {
  
  let arr = [];
    for(let i=n; i>0;i--){
      arr.push(i)
    } return arr;
};
  
//Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.
//The output should be two capital letters with a dot separating them.
//It should look like this:
//Sam Harris => S.H
//patrick feeney => P.F

function abbrevName(name){
  let initials = name.split(" ")
  return initials[0].charAt(0).toUpperCase()+'.' + initials[1].charAt(0).toUpperCase(); 
    
}
//Implement a function which convert the given boolean value into its string representation.
//Note: Only valid inputs will be given.

function booleanToString(b){
  const b = new Boolean(true);
  
console.log(b.toString())
}
//Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love.

//Write a function that will take the number of petals of each flower and return true if they are in love and false if they aren't.




function lovefunc(flower1,flower2){
    if (flower1%2==0&&flower2%2!==0) {
        return true;
    }else if(flower1%2!==0&&flower2%2==0){
        return true;
    }else return false;
}

//  Best practice
//function lovefunc(flower1, flower2){
//  return flower1 % 2 !== flower2 % 2;
//}
//Very simple, given an integer or a floating-point number, find its opposite.
//Examples:
//1: -1
//14: -14
//-34: 34

function opposite(number){
let oppNum = 0 - number
return oppNum;
}
//While loop loops through a block of code as long as a specified condition is true

//Syntax
while (condition){
  //code block to be executed
}

while (i < 10){
  text += "The number is" +i;
ii+
}
// Setup
const myArray = [];

for(let i = 1;i<10; i +=2){
  myArray.push(i)
}

//The JS "for in" statement loops through the properties of an Object:

//Syntax
for (key in object){
  //code block to be executed
}

const person = {first_name: "John", last_name: "Doe", age:25};

let text = "";
for (let x in person) {
  text += person[x]
}

//John Doe 25

// Example explained
-   The for in loop iterates over a person object
-   Each iteration returns a key (x)
-   The key is used to access the value of the key
-   The value of the key is person[x]

//For in over arrays
for (variable in array){
  code
}

const numbers = [45,4,9]

let txt = "";
for (let x in numbers){
  txt += numbers[x]
}

// 45
//  4
//  9

//NOTE: It is better to use a "for" loop, a "for of" loop, or "Array.forEach()" when the order matters


///Array.forEach()
//forEach() method calls a function (a callback function) once for each array element
const numbers = [45,4,9]

let txt = "" (or let arr = []);
numbers.forEach(myFunction);

function myFunction(value, index, array){
  txt += value;
}
//Instead of writing
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";

for (let i = 0; i < cars.length; i++{
  text += cars[i] + "<br>";
}
     
syntax: for(statement 1; statement 2; statement 3){
  //code block to be executed
}     
     
//Statement 1 initializes the variable used in the loop (let i = 0). Many values can be initiated (separated by coma)
     
//Statement 2 evaluates the condition of the inital value. If it returns true, the loop will start over again, if it returns false, the loop wil end
     
//Statement 3 increments the value of the inital variable. It can do anything like negative increment (i--), and positive increment (i = i +15)
	const { data: cryptoList, isFetching } = useGetCryptosQuery(count);
	const [cryptos, setCryptos] = useState([]);
	const [searchTerm, setSearchTerm] = useState("");

	useEffect(() => {
		setCryptos(cryptoList?.data?.coins);

		const filteredData = cryptoList?.data?.coins.filter((coin) =>
			coin.name.toLowerCase().includes(searchTerm.toLowerCase())
		);

		setCryptos(filteredData);
	}, [cryptoList, searchTerm]);
const student = {
    name: 'Monica',
    class: 7,
    age: 12
}

// using for...in
for ( let key in student ) {

    // display the properties
    console.log(`${key} => ${student[key]}`);
}
const student = {
    name: 'Monica',
    class: 7,
    age: 12
}

// using for...in
for ( let key in student ) {

    // display the properties
    console.log(`${key} => ${student[key]}`);
}
//componentDidMount
useEffect(() => {
    console.log("Behavior before the component is added to the DOM");
  }, []);

//componentDidUpdate
useEffect(() => {
    console.log("Behavior when the component receives new state or props.");
  });

//Or

useEffect(() => {
    console.log("Behavior when the value of 'stateName' changes.");
  }, [stateName]);

//Or
import React, { useEffect, useRef } from "react"
const mounted = useRef()
useEffect(() => {
  if (!mounted.current) {
    // do componentDidMount logic
    mounted.current = true
  } else {
    // do componentDidUpdate logic
  }
})

//componentWillUnmount
useEffect(() => {
    return () => {
            console.log("Behavior right before the component is removed from the DOM.");
        }
  }, []);

//Putting it all together
  useEffect(() => {
    const intervalId = setInterval(() => {
      document.title = `Time is: ${new Date()}`;
    }, 1000);
 
    return () => {
      document.title = "Time stopped.";
      clearInterval(intervalId);
    }
  }, []);
star

Thu Jun 30 2022 06:50:06 GMT+0000 (UTC)

#javascriptreact
star

Thu Jun 30 2022 06:45:47 GMT+0000 (UTC)

#javascriptreact #react.js
star

Thu Jun 30 2022 06:45:19 GMT+0000 (UTC)

#javascriptreact
star

Mon Jun 06 2022 10:40:05 GMT+0000 (UTC)

#javascriptreact
star

Sun May 22 2022 21:41:26 GMT+0000 (UTC)

#javascriptreact
star

Sun May 22 2022 21:23:44 GMT+0000 (UTC)

#javascriptreact
star

Thu May 12 2022 23:21:25 GMT+0000 (UTC)

#javascriptreact
star

Thu May 12 2022 17:34:46 GMT+0000 (UTC)

#javascriptreact
star

Sat May 07 2022 22:24:42 GMT+0000 (UTC)

#javascriptreact
star

Sat May 07 2022 15:53:25 GMT+0000 (UTC)

#javascriptreact
star

Sat May 07 2022 15:19:52 GMT+0000 (UTC)

#javascriptreact
star

Sat May 07 2022 14:57:01 GMT+0000 (UTC)

#javascriptreact
star

Sat May 07 2022 14:44:52 GMT+0000 (UTC)

#javascriptreact
star

Sat May 07 2022 12:18:38 GMT+0000 (UTC)

#javascriptreact
star

Sat May 07 2022 11:49:33 GMT+0000 (UTC)

#javascriptreact
star

Thu May 05 2022 15:00:42 GMT+0000 (UTC)

#javascriptreact
star

Wed May 04 2022 09:56:50 GMT+0000 (UTC)

#javascriptreact
star

Wed May 04 2022 09:44:40 GMT+0000 (UTC)

#javascriptreact
star

Wed May 04 2022 09:34:43 GMT+0000 (UTC)

#javascriptreact
star

Wed May 04 2022 09:27:29 GMT+0000 (UTC)

#javascriptreact
star

Wed May 04 2022 09:03:21 GMT+0000 (UTC)

#javascriptreact
star

Wed Apr 27 2022 15:41:32 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 26 2022 22:37:41 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 26 2022 14:09:47 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 19 2022 14:11:08 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 12 2022 17:13:26 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 12 2022 12:30:13 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 12 2022 12:09:24 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 12 2022 11:37:15 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 12 2022 11:33:15 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 12 2022 11:30:36 GMT+0000 (UTC)

#javascriptreact
star

Mon Apr 11 2022 21:01:04 GMT+0000 (UTC)

#javascriptreact
star

Mon Apr 11 2022 20:58:35 GMT+0000 (UTC)

#javascriptreact
star

Mon Apr 11 2022 20:52:10 GMT+0000 (UTC)

#javascriptreact
star

Mon Apr 11 2022 20:29:13 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 27 2021 11:01:26 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 27 2021 11:01:24 GMT+0000 (UTC)

#javascriptreact
star

Tue Apr 27 2021 10:38:17 GMT+0000 (UTC) https://blog.carbonfive.com/replacing-component-lifecycle-methods-with-react-hooks/

#javascriptreact #react.js

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension