Snippets Collections
export function TailwindIndicator() {
  if (process.env.NODE_ENV === "production") return null

  return (
    <div className="fixed bottom-1 left-1 z-50 flex h-6 w-6 items-center justify-center rounded-full bg-gray-800 p-3 font-mono text-xs text-white">
      <div className="block sm:hidden">xs</div>
      <div className="hidden sm:block md:hidden">sm</div>
      <div className="hidden md:block lg:hidden">md</div>
      <div className="hidden lg:block xl:hidden">lg</div>
      <div className="hidden xl:block 2xl:hidden">xl</div>
      <div className="hidden 2xl:block">2xl</div>
    </div>
  )
}
import { useState } from "react";

function useGeolocation() {
  const [isLoading, setIsLoading] = useState(false);
  const [position, setPosition] = useState({});
  const [error, setError] = useState(null);

  function getPosition() {
    if (!navigator.geolocation)
      return setError("Your browser does not support geolocation");

    setIsLoading(true);
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        setPosition({
          lat: pos.coords.latitude,
          lng: pos.coords.longitude
        });
        setIsLoading(false);
      },
      (error) => {
        setError(error.message);
        setIsLoading(false);
      }
    );
  }

  return { isLoading, position, error, getPosition };
}

export default function App() {
  const {
    isLoading,
    position: { lat, lng },
    error,
    getPosition
  } = useGeolocation();

  const [countClicks, setCountClicks] = useState(0);

  function handleClick() {
    setCountClicks((count) => count + 1);
    getPosition();
  }

  return (
    <div>
      <button onClick={handleClick} disabled={isLoading}>
        Get my position
      </button>

      {isLoading && <p>Loading position...</p>}
      {error && <p>{error}</p>}
      {!isLoading && !error && lat && lng && (
        <p>
          Your GPS position:{" "}
          <a
            target="_blank"
            rel="noreferrer"
            href={`https://www.openstreetmap.org/#map=16/${lat}/${lng}`}
          >
            {lat}, {lng}
          </a>
        </p>
      )}

      <p>You requested position {countClicks} times</p>
    </div>
  );
}
import { createContext } from "react";
import useFetch from '../hooks/useFetch' // import the useFetch hook


const BASE_URL = 'http://localhost:8000';


const CitiesContext = createContext();



function CitiesProvider({children}){

    // fetch hook for cities => see useFetchCties file
    const {data: cities, loading, error} = useFetch(`${BASE_URL}/cities`);  


    return(
      <CitiesContext.Provider value={{
          cities: cities,
          loading: loading,
          error: error
      }}>

        {children}
      </CitiesContext.Provider>
    )
}

export {CitiesContext, CitiesProvider}

import { createContext, useState } from "react";
import { faker } from "@faker-js/faker";



//1. create the context
const PostContext = createContext();


// 2. create  the Provider function that returns the provider
function PostProvider({children}){


  // 3. add all state and functions we need
  const [posts, setPosts] = useState(() =>
    Array.from({ length: 30 }, () => createRandomPost())
  );

  const [searchQuery, setSearchQuery] = useState("");

  // Derived state. These are the posts that will actually be displayed
  const searchedPosts = searchQuery.length > 0 ? posts.filter((post) => `${post.title} ${post.body}`.toLowerCase().includes(searchQuery.toLowerCase())) : posts;

  function handleAddPost(post) {
    setPosts((posts) => (
      [...posts, post]
    ))
  }

  function handleClearPosts() {
    setPosts([]);
  }

  function createRandomPost() {
    return {
      title: `${faker.hacker.adjective()} ${faker.hacker.noun()}`,
      body: faker.hacker.phrase(),
    };
  }


   // 4. return all values we need to the provider
   // the values represent all state and functions we have above using an object
   // then we call each key inside the wrapped component where each state or function is needed

  return(
    <PostContext.Provider value={{
      posts: searchedPosts, // the derived state that holds the posts
      query: searchQuery, // the query
      querySetter: setSearchQuery, // query setter function
      addPostHandler: handleAddPost, // add post function
      clearPostHander: handleClearPosts, // clear posts function
    }}>
      {children}
    </PostContext.Provider>
  )

  
} // close the PostProvider function


// 5.export the postContext to use AND the Provider to wrap all components
export {PostContext, PostProvider} 
  // Derived state. These are the posts that will actually be displayed
  const searchedPosts = searchQuery.length > 0 ? posts.filter((post) => `${post.title} ${post.body}`.toLowerCase().includes(searchQuery.toLowerCase())) : posts;
import React fron "react";

type ButtonOrLinkProps = | (React.ButtonHTMLAttributes<HTMLButtonElement> & { as?: "Button"}) | (React.AnchorHTMLAttrributes<HTMLAnchorElement>) & { as: "a"});

const ButtonOrLink = (props: ButtonOrLinkProps) => {
  if(props.as === "a"){
    return <a {...props} />
  }
  return <button {...props} />
}

/** Use case */
<ButtonOrLink  onClick={(e) => {console.log(e)}}/>
<ButtonOrLink as="a"  onClick={(e) => {console.log(e)}}/>
  
import { createContext, useState } from "react";

export const ThemeContext = createContext();

// pass the prop children; a provider is needed here
export default function ThemeContextProvider({ children }) {
  
  // boolean for default setting
  const [darkMode, setDarkMode] = useState(true);
  return (
    // allows darkMode and setDarkMode to be used
    <ThemeContext.Provider value={{ darkMode, setDarkMode }}>
      {children}
    </ThemeContext.Provider>
  );
}
// place within vite.config.js

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  css: {
    modules: {
      localsConvention: "camelCase",
    },
  },
});
import { StyleSheet, Text, View, SafeAreaView, Pressable } from "react-native";
import React, { useEffect, useState } from "react";
import { LinearGradient } from "expo-linear-gradient";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useNavigation } from "@react-navigation/native";
import * as WebBrowser from "expo-web-browser";
import { useAuthRequest } from "expo-auth-session";
import axios from "axios";
import base64 from "base-64";

import { CLIENT_ID, REDIRECT_URL, CLIENT_SECRET } from "@env";
import { Entypo, MaterialIcons, AntDesign } from "@expo/vector-icons";

WebBrowser.maybeCompleteAuthSession();

const discovery = {
  authorizationEndpoint: "https://accounts.spotify.com/authorize",
  tokenEndpoint: "https://accounts.spotify.com/api/token",
};

const LoginScreen = () => {
  const navigation = useNavigation();

  useEffect(() => {
    const checkTokenValidity = async () => {
      const accessToken = await AsyncStorage.getItem("token");
      const expirationDate = await AsyncStorage.getItem("expirationDate");
      console.log("access token: ", accessToken);
      console.log("expiration date: ", expirationDate);

      if (accessToken && expirationDate) {
        const currentTime = Date.now();
        if (currentTime < parseInt(expirationDate)) {
          // token is valid
          navigation.replace("Main");
        } else {
          // token expired
          AsyncStorage.removeItem("token");
          AsyncStorage.removeItem("expirationDate");
        }
      }
    };
    checkTokenValidity();
  }, []);

  const [request, response, promptAsync] = useAuthRequest(
    {
      clientId: CLIENT_ID,
      scopes: [
        "user-read-email",
        "user-library-read",
        "user-top-read",
        "user-read-recently-played",
        "playlist-read-private",
        "playlist-read-collaborative",
        "playlist-modify-public",
        // "playlist-modify-private",
      ],
      usePKCE: false,
      redirectUri: REDIRECT_URL,
      clientSecret: CLIENT_SECRET,
    },
    discovery
  );

  const handleAuth = async () => {
    if (promptAsync) {
      const result = await promptAsync();
      console.log(result);

      if (result) {
        console.log("checkkk")
        const { code } = result.params;
        
        try {
          const authOptions = {
            url: 'https://accounts.spotify.com/api/token',
            headers: {
              'Authorization': 'Basic ' + (base64.encode(CLIENT_ID + ':' + CLIENT_SECRET)),
              "Content-Type": "application/x-www-form-urlencoded",
            },
            form: {
              grant_type: 'client_credentials'
            },
            json: true,
            data: `grant_type=authorization_code&code=${code}&redirect_uri=${REDIRECT_URL}`
          };
          const res = await axios.post(authOptions);
          console.log("chala ",res);
        } catch (error) {
          console.log(error)
        }
        
        const expirationDate = Date.now() + parseInt(expires_in) * 1000;

        if (code && expirationDate) {
          AsyncStorage.setItem("token", code);
          AsyncStorage.setItem("expirationDate", expirationDate.toString());
          navigation.navigate("Main");
        } else {
          console.error("Invalid access token or expiration date.");
        }
      } else {
        console.error("Authentication error:", result.error);
      }
    }
  };

  return (
    <LinearGradient colors={["#040306", "#131624"]} style={{ flex: 1 }}>
      <SafeAreaView>
        <View style={{ height: 80 }} />
        <Entypo
          style={{ textAlign: "center" }}
          name="spotify"
          size={80}
          color="white"
        />
        <Text
          style={{
            color: "white",
            fontSize: 40,
            fontWeight: "bold",
            textAlign: "center",
            marginTop: 40,
          }}
        >
          Millions of Songs Free on Spotify
        </Text>

        <View style={{ height: 80 }} />
        <Pressable
          onPress={handleAuth}
          style={{
            backgroundColor: "#1DB954",
            padding: 10,
            marginLeft: "auto",
            marginRight: "auto",
            width: 300,
            borderRadius: 25,
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Text>Sign In with Spotify</Text>
        </Pressable>

        <Pressable
          style={{
            backgroundColor: "#131624",
            padding: 10,
            marginLeft: "auto",
            marginRight: "auto",
            width: 300,
            borderRadius: 25,
            alignItems: "center",
            justifyContent: "center",
            flexDirection: "row",
            marginVertical: 10,
            borderColor: "#C0C0C0",
            borderWidth: 0.8,
          }}
        >
          <MaterialIcons name="phone-android" size={24} color="white" />
          <Text
            style={{
              fontWeight: "500",
              color: "white",
              textAlign: "center",
              flex: 1,
            }}
          >
            Continue with phone number
          </Text>
        </Pressable>

        <Pressable
          style={{
            backgroundColor: "#131624",
            padding: 10,
            marginLeft: "auto",
            marginRight: "auto",
            width: 300,
            borderRadius: 25,
            alignItems: "center",
            justifyContent: "center",
            flexDirection: "row",
            marginVertical: 10,
            borderColor: "#C0C0C0",
            borderWidth: 0.8,
          }}
        >
          <AntDesign name="google" size={24} color="red" />
          <Text
            style={{
              fontWeight: "500",
              color: "white",
              textAlign: "center",
              flex: 1,
            }}
          >
            Continue with Google
          </Text>
        </Pressable>

        <Pressable
          style={{
            backgroundColor: "#131624",
            padding: 10,
            marginLeft: "auto",
            marginRight: "auto",
            width: 300,
            borderRadius: 25,
            alignItems: "center",
            justifyContent: "center",
            flexDirection: "row",
            marginVertical: 10,
            borderColor: "#C0C0C0",
            borderWidth: 0.8,
          }}
        >
          <Entypo name="facebook" size={24} color="blue" />
          <Text
            style={{
              fontWeight: "500",
              color: "white",
              textAlign: "center",
              flex: 1,
            }}
          >
            Continue with Facebook
          </Text>
        </Pressable>
      </SafeAreaView>
    </LinearGradient>
  );
};

export default LoginScreen;

const styles = StyleSheet.create({});
import { StyleSheet, Text, View, SafeAreaView, Pressable } from "react-native";
import React, { useEffect } from "react";
import { LinearGradient } from "expo-linear-gradient";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useNavigation } from "@react-navigation/native";
import * as WebBrowser from "expo-web-browser";
import { makeRedirectUri, useAuthRequest } from "expo-auth-session";

import { CLIENT_ID, REDIRECT_URL } from "@env";
import { Entypo, MaterialIcons, AntDesign } from "@expo/vector-icons";

WebBrowser.maybeCompleteAuthSession();

const discovery = {
  authorizationEndpoint: "https://accounts.spotify.com/authorize",
  tokenEndpoint: "https://accounts.spotify.com/api/token",
};

const LoginScreen = () => {
  const navigation = useNavigation();

  useEffect(() => {
    const checkTokenValidity = async () => {
      const accessToken = await AsyncStorage.getItem("token");
      const expirationDate = await AsyncStorage.getItem("expirationDate");
      console.log("access token: ", accessToken);
      console.log("expiration date: ", expirationDate);

      if (accessToken && expirationDate) {
        const currentTime = Date.now();
        if (currentTime < parseInt(expirationDate)) {
          // token is valid
          navigation.replace("Main");
        } else {
          // token expired
          AsyncStorage.removeItem("token");
          AsyncStorage.removeItem("expirationDate");
        }
      }
    };
    checkTokenValidity();
  }, []);

  async function handleAuth() {
    /*const config = {
      issuer: "https://accounts.spotify.com",
      clientId: CLIENT_ID,
      scopes: [
    "user-read-email",
    "user-library-read",
    "user-top-read",
    "user-read-recently-played",
    "playlist-read-private",
    "playlist-read-collaborative",
    "playlist-modify-public",
    // "playlist-modify-private",
      ],
      redirectUrl: REDIRECT_URL
    };

    const result = await AppAuth.authAsync(config);*/
    
    const [request, response, promptAsync] = useAuthRequest({
      clientId: CLIENT_ID,
      scopes: [
        "user-read-email",
        "user-library-read",
        "user-top-read",
        "user-read-recently-played",
        "playlist-read-private",
        "playlist-read-collaborative",
        "playlist-modify-public",
        // "playlist-modify-private",
      ],
      usePKCE: false,
      redirectUri: REDIRECT_URL,
    }, discovery);
    console.log(response);

    /*if (result.accessToken) {
      const expirationDate = new Date(
        result.accessTokenExpirationDate
      ).getTime();
      AsyncStorage.setItem("token", result.accessToken);
      AsyncStorage.setItem("expirationDate", expirationDate.toString());
      navigation.navigate("Main");
    }*/
  }

  return (
    <LinearGradient colors={["#040306", "#131624"]} style={{ flex: 1 }}>
      <SafeAreaView>
        <View style={{ height: 80 }} />
        <Entypo
          style={{ textAlign: "center" }}
          name="spotify"
          size={80}
          color="white"
        />
        <Text
          style={{
            color: "white",
            fontSize: 40,
            fontWeight: "bold",
            textAlign: "center",
            marginTop: 40,
          }}
        >
          Millions of Songs Free on Spotify
        </Text>

        <View style={{ height: 80 }} />
        <Pressable
          onPress={handleAuth}
          style={{
            backgroundColor: "#1DB954",
            padding: 10,
            marginLeft: "auto",
            marginRight: "auto",
            width: 300,
            borderRadius: 25,
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Text>Sign In with Spotify</Text>
        </Pressable>

        <Pressable
          style={{
            backgroundColor: "#131624",
            padding: 10,
            marginLeft: "auto",
            marginRight: "auto",
            width: 300,
            borderRadius: 25,
            alignItems: "center",
            justifyContent: "center",
            flexDirection: "row",
            marginVertical: 10,
            borderColor: "#C0C0C0",
            borderWidth: 0.8,
          }}
        >
          <MaterialIcons name="phone-android" size={24} color="white" />
          <Text
            style={{
              fontWeight: "500",
              color: "white",
              textAlign: "center",
              flex: 1,
            }}
          >
            Continue with phone number
          </Text>
        </Pressable>

        <Pressable
          style={{
            backgroundColor: "#131624",
            padding: 10,
            marginLeft: "auto",
            marginRight: "auto",
            width: 300,
            borderRadius: 25,
            alignItems: "center",
            justifyContent: "center",
            flexDirection: "row",
            marginVertical: 10,
            borderColor: "#C0C0C0",
            borderWidth: 0.8,
          }}
        >
          <AntDesign name="google" size={24} color="red" />
          <Text
            style={{
              fontWeight: "500",
              color: "white",
              textAlign: "center",
              flex: 1,
            }}
          >
            Continue with Google
          </Text>
        </Pressable>

        <Pressable
          style={{
            backgroundColor: "#131624",
            padding: 10,
            marginLeft: "auto",
            marginRight: "auto",
            width: 300,
            borderRadius: 25,
            alignItems: "center",
            justifyContent: "center",
            flexDirection: "row",
            marginVertical: 10,
            borderColor: "#C0C0C0",
            borderWidth: 0.8,
          }}
        >
          <Entypo name="facebook" size={24} color="blue" />
          <Text
            style={{
              fontWeight: "500",
              color: "white",
              textAlign: "center",
              flex: 1,
            }}
          >
            Continue with Facebook
          </Text>
        </Pressable>
      </SafeAreaView>
    </LinearGradient>
  );
};

export default LoginScreen;

const styles = StyleSheet.create({});
utils.waitForElement('#app-root').then((root) => utils.waitUntil(() => root._reactRootContainer)).then(() => {
    // MOBILE - RENTAL MANAGER
    utils.observeSelector(`.Link-signIn a[title='Sign in']`, (signInBtn) => {
      signInBtn.innerText = v1Text;
    });

    // DESKTOP - RENTAL MANAGER
    utils.waitForElement(`a[title='Sign in']`).then((signInBtn) => {
      signInBtn.innerText = v1Text;
    }).catch(error);
  }).catch(error);
const subMenuItems = (items) => {

    return items?.map((menu) => {

      return menu?.childMenus.length

        ? getItem(menu.name, menu.name, subMenuItems(menu?.childMenus))

        : getItem(

            <HashLink

              to={menu.URL}

              onClick={() => {

                if (

                  menu.name.toLowerCase() == MENU_TEXT.OFFERINGS.toLowerCase()

                ) {

                  removeOfferingFilter();

                } else if (

                  menu.name.toLowerCase() == MENU_TEXT.IPOS.toLowerCase()

                ) {

                  removeIpoFilter();

                }

              }}
            >
              {menu.name}

            </HashLink>,

            menu.name

          );

    });

  };
As written in font awesome documentation, you can easily use it like this:
First, install the package by:

npm install @fortawesome/fontawesome-svg-core
npm install @fortawesome/free-solid-svg-icons
npm install @fortawesome/react-fontawesome

Then you can use it like this:

Then you can use it like this:

  // Light:
  <FontAwesomeIcon icon={["fal", "coffee"]} />
  // Regular:
  <FontAwesomeIcon icon={["far", "coffee"]} />
  // Solid
  <FontAwesomeIcon icon={["fas", "coffee"]} />
  // ...or, omit as FontAwesome defaults to solid, so no need to prefix:
  <FontAwesomeIcon icon="coffee" />
  // Brand:
  <FontAwesomeIcon icon={["fab", "github"]} />
You can also use it like this:

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCoffee } from '@fortawesome/free-solid-svg-icons'

const element = <FontAwesomeIcon icon={faCoffee} />
Sizing:

  <FontAwesomeIcon icon="coffee" size="xs" />
  <FontAwesomeIcon icon="coffee" size="lg" />
  <FontAwesomeIcon icon="coffee" size="6x" />
import { useState } from "react"

export default function useToggle(defaultValue) {
  const [value, setValue] = useState(defaultValue)

  function toggleValue(value) {
    setValue(currentValue =>
      typeof value === "boolean" ? value : !currentValue
    )
  }

  return [value, toggleValue]
}
"emmet.includeLanguages": {
  "javascript": "javascriptreact"
 }

or 

"emmet.includeLanguages": {
  "javascript": "javascriptreact",
  "typescript": "typescriptreact"
}
const selected = querySelector('selected');
  const prev =
    selected.previousElementSibling || this.modalImages.lastElementChild;
  selected.classList.remove('selected');
  prev.classList.add('selected');
import { Pagination } from "antd";

const [currentPage, setCurrentPage] = useState(1);
  const [itemPerPage, setItemPerPage] = useState(25);

const indexOfLastItem = currentPage * itemPerPage;
  const indexOfFirstItem = indexOfLastItem - itemPerPage;
  const currentItem = users.slice(indexOfFirstItem, indexOfLastItem);

//IMP. NOTE {(curretitem.map)map also run by curretitem}

    <Pagination
                total={users.length}
                current={currentPage}
                pageSize={itemPerPage}
                onChange={(currentPage) => setCurrentPage(currentPage)}
              />



@import "antd/dist/antd.css";

.ant-spin-nested-loading {
  width: 100%;
  height: 100vh;
  background-image: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3));
}

.ant-alert-info {
  background-image: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3));
  border: none;
}
.ant-spin-nested-loading > div > .ant-spin .ant-spin-dot {
  top: 100%;
}
.ant-spin-text {
  top: 100% !important;
  color: rgb(11, 11, 11);
  font-weight: bold;
  font-size: 110%;
}
.ant-spin-dot-item {
  background-color: rgb(11, 11, 11);
}


import { Alert, Spin } from 'antd';
import React from 'react';
const App = () => (
  <Spin tip="Loading...">
    <Alert
    
    />
  </Spin>
);
export default App;
import React, { useState } from 'react';

const Tour = ({ id, image, info, name, price, removeTour }) => {
  const [readMore, setReadMore] = useState(false);
  return (
    <article className="single-tour">
      <img src={image} alt={name} />
      <footer>
        <div className="tour-info">
          <h4>{name}</h4>
          <h4 className="tour-price">${price}</h4>
        </div>
        <p>
          {readMore ? info : `${info.substring(0, 200)}...`}
          <button onClick={() => setReadMore(!readMore)}>
            {readMore ? 'show less' : '  read more'}
          </button>
        </p>
        <button className="delete-btn" onClick={() => removeTour(id)}>
          not interested
        </button>
      </footer>
    </article>
  );
};

export default Tour;
import React, { useState, useEffect } from 'react';


const UseEffectCleanup = () => {
  
  const [width, setWidth] = useState(window.innerWidth);

  const checkSize = () => {
    setWidth(window.innerWidth)
  }

  useEffect(() => {

    window.addEventListener('resize', checkSize)
    return () => {
      window.removeEventListener('resize', checkSize)
    }
  }, [width]);

  return (
    <>
      <h1>Window Size</h1>
      <h2>{`${width}px`}</h2>
    </>
  );

}


export default UseEffectCleanup;
    let selectColor = '';
    let selectCategory = '';

    const getColor = (metadata) => {
        if (metadata !== undefined) {
            if (metadata.length > 1) {
                selectColor = 'orange';
            } else {
                switch (metadata[0]) {
                    case 'stageEarlyChildhood':
                        selectColor = 'pink';
                        break;
                    case 'stagePrimarySchool':
                        selectColor = 'green';
                        break;
                    case 'stageSecondarySchool':
                        selectColor = 'red';
                        break;
                    case 'stageLearnerNoviceDriver':
                        selectColor = 'blue';
                        break;
                    default:
                        selectColor = 'orange';
                        break;
                }
            }
        }
    };
getColor(object.somevalue.that.has.an.array);
npm install rc-tween-one --save
npm install rc-banner-anim
.custom-arrow-thumb {
  height: 220px;
}
.custom-arrow-thumb .user-arrow {
  top: 50%;
  margin-top: -40px;
}
.custom-arrow-thumb .user-arrow .img-wrapper {
  width: 120px;
  height: 80px;
  float: left;
  position: relative;
}
.custom-arrow-thumb .user-arrow .img-wrapper li {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  position: absolute;
}
.custom-arrow-thumb .user-arrow .arrow {
  width: 20px;
  height: 80px;
  background: rgba(0, 0, 0, 0.3);
  position: relative;
}
.custom-arrow-thumb .user-arrow .arrow:before,
.custom-arrow-thumb .user-arrow .arrow:after {
  width: 2px;
  height: 15px;
  background: #fff;
  display: block;
  content: " ";
  position: absolute;
}
.custom-arrow-thumb .user-arrow.next {
  right: -120px;
}
.custom-arrow-thumb .user-arrow.next .arrow {
  float: left;
}
.custom-arrow-thumb .user-arrow.next .arrow:before {
  -webkit-transform: rotate(-40deg);
  transform: rotate(-40deg);
  top: 28px;
  left: 10px;
}
.custom-arrow-thumb .user-arrow.next .arrow:after {
  -webkit-transform: rotate(40deg);
  transform: rotate(40deg);
  bottom: 27px;
  left: 10px;
}
.custom-arrow-thumb .user-arrow.prev {
  left: -120px;
}
.custom-arrow-thumb .user-arrow.prev .arrow {
  float: right;
}
.custom-arrow-thumb .user-arrow.prev .arrow:before {
  -webkit-transform: rotate(40deg);
  transform: rotate(40deg);
  top: 28px;
  left: 8px;
}
.custom-arrow-thumb .user-arrow.prev .arrow:after {
  -webkit-transform: rotate(-40deg);
  transform: rotate(-40deg);
  bottom: 27px;
  left: 8px;
}
.custom-arrow-thumb .user-thumb {
  overflow: hidden;
  background: rgba(255, 255, 255, 0.15);
  height: 40px;
}
.custom-arrow-thumb .user-thumb > span {
  width: 50px;
  height: 30px;
  margin: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
  -webkit-transition: background 0.3s;
  transition: background 0.3s;
  background: transparent;
}
.custom-arrow-thumb .user-thumb > span.active {
  background: rgba(255, 255, 255, 0.45);
}
.custom-arrow-thumb .user-thumb > span i {
  display: block;
  width: 46px;
  height: 26px;
  margin: 2px;
  background-size: cover;
  background-position: center;
}

.bg {
  height: 100vh !important;
}

.banner-anim {
  height: 90vh;
}

#banner-user-text {
  color: #fff;
}

.banner-user-title {
  position: absolute !important;
  font-size: 900% !important;
  top: 30% !important;
  left: 10%;
  color: rgb(244, 244, 244) !important;
}
.banner-user-text {
  position: absolute !important;
  font-size: 900% !important;
  top: 40% !important;
  left: 10%;
  color: rgb(150, 150, 150) !important;
}
import React from "react";

import { ReactDOM } from "react";
import BannerAnim from "rc-banner-anim";
import TweenOne, { TweenOneGroup } from "rc-tween-one";
import "../header/Header.css";
import "rc-banner-anim/assets/index.css";
const { Element, Arrow, Thumb } = BannerAnim;
const BgElement = Element.BgElement;
class Header extends React.Component {
  constructor() {
    super(...arguments);
    this.imgArray = [
      "https://zos.alipayobjects.com/rmsportal/hzPBTkqtFpLlWCi.jpg",
      "https://zos.alipayobjects.com/rmsportal/gGlUMYGEIvjDOOw.jpg",
    ];
    this.state = {
      intShow: 0,
      prevEnter: false,
      nextEnter: false,
      thumbEnter: false,
    };
    [
      "onChange",
      "prevEnter",
      "prevLeave",
      "nextEnter",
      "nextLeave",
      "onMouseEnter",
      "onMouseLeave",
    ].forEach((method) => (this[method] = this[method].bind(this)));
  }

  onChange(type, int) {
    if (type === "before") {
      this.setState({
        intShow: int,
      });
    }
  }

  getNextPrevNumber() {
    let nextInt = this.state.intShow + 1;
    let prevInt = this.state.intShow - 1;
    if (nextInt >= this.imgArray.length) {
      nextInt = 0;
    }
    if (prevInt < 0) {
      prevInt = this.imgArray.length - 1;
    }

    return [prevInt, nextInt];
  }

  prevEnter() {
    this.setState({
      prevEnter: true,
    });
  }

  prevLeave() {
    this.setState({
      prevEnter: false,
    });
  }

  nextEnter() {
    this.setState({
      nextEnter: true,
    });
  }

  nextLeave() {
    this.setState({
      nextEnter: false,
    });
  }

  onMouseEnter() {
    this.setState({
      thumbEnter: true,
    });
  }

  onMouseLeave() {
    this.setState({
      thumbEnter: false,
    });
  }

  render() {
    const intArray = this.getNextPrevNumber();
    const thumbChildren = this.imgArray.map((img, i) => (
      <span key={i}>
        <i style={{ backgroundImage: `url(${img})` }} />
      </span>
    ));
    return (
      <BannerAnim
        onChange={this.onChange}
        onMouseEnter={this.onMouseEnter}
        onMouseLeave={this.onMouseLeave}
        prefixCls="custom-arrow-thumb"
      >
        <Element key="aaa" prefixCls="banner-user-elem">
          <BgElement
            key="bg"
            className="bg"
            style={{
              backgroundImage: `url(${this.imgArray[0]})`,
              backgroundSize: "cover",
              backgroundPosition: "center",
            }}
          />
          <TweenOne
            className="banner-user-title"
            animation={{ y: 30, opacity: 0, type: "from" }}
          >
            Ant Motion Banner
          </TweenOne>
          <TweenOne
            className="banner-user-text"
            animation={{ y: 30, opacity: 0, type: "from", delay: 100 }}
          >
           Poka
          </TweenOne>
        </Element>
        <Element key="bbb" prefixCls="banner-user-elem">
          <BgElement
            key="bg"
            className="bg"
            style={{
              backgroundImage: `url(${this.imgArray[1]})`,
              backgroundSize: "cover",
              backgroundPosition: "center",
            }}
          />
          <TweenOne
            className="banner-user-title"
            animation={{ y: 30, opacity: 0, type: "from" }}
          >
            Ant Motion Banner
          </TweenOne>
          <TweenOne
            className="banner-user-text"
            animation={{ y: 30, opacity: 0, type: "from", delay: 100 }}
          >
            The Fast Way Use Animation In React
          </TweenOne>
        </Element>
        <Arrow
          arrowType="prev"
          key="prev"
          prefixCls="user-arrow"
          component={TweenOne}
          onMouseEnter={this.prevEnter}
          onMouseLeave={this.prevLeave}
          animation={{ left: this.state.prevEnter ? 0 : -120 }}
        >
          <div className="arrow"></div>
          <TweenOneGroup
            enter={{ opacity: 0, type: "from" }}
            leave={{ opacity: 0 }}
            appear={false}
            className="img-wrapper"
            component="ul"
          >
            <li
              style={{ backgroundImage: `url(${this.imgArray[intArray[0]]})` }}
              key={intArray[0]}
            />
          </TweenOneGroup>
        </Arrow>
        <Arrow
          arrowType="next"
          key="next"
          prefixCls="user-arrow"
          component={TweenOne}
          onMouseEnter={this.nextEnter}
          onMouseLeave={this.nextLeave}
          animation={{ right: this.state.nextEnter ? 0 : -120 }}
        >
          <div className="arrow"></div>
          <TweenOneGroup
            enter={{ opacity: 0, type: "from" }}
            leave={{ opacity: 0 }}
            appear={false}
            className="img-wrapper"
            component="ul"
          >
            <li
              style={{ backgroundImage: `url(${this.imgArray[intArray[1]]})` }}
              key={intArray[1]}
            />
          </TweenOneGroup>
        </Arrow>
        <Thumb
          prefixCls="user-thumb"
          key="thumb"
          component={TweenOne}
          animation={{ bottom: this.state.thumbEnter ? 0 : -70 }}
        >
          {thumbChildren}
        </Thumb>
      </BannerAnim>
    );
  }
}
export default Header;
const [showDialog, setShowDialog] = useState(true);

<DisclaimerModal
     text='...'
     showDialog={showDialog}
     handleAccept={() => setShowDialog(false)}
     handleDecline={() => setShowDialog(false)}
/>

const App = () => {
  return(
    <Router>
      <Routes>
        <Route path="/component1" element={<Component1 />} />
		<Route path="/component2/:data" element={<Component2 />} />
      </Routes>
    </Router>
  )
}
const Component2 = () => {
  const { data } = useParams();
  return(
    <div>
      <h2>The data is: {data}</h2>
    </div>
  )
}
//HTML
<div class='dropdown'>
          <Link id='product' className='every' to='/products'>OUR PRODUCTS</Link>
           <div class='dropdown-content'>
            <Link to='autocadd'>AutoCadd</Link>
            <Link to='techset'>Techset</Link>
            <Link to='Endorse'>Endorse</Link>
           </div>
          </div>

//CSS

.dropdown{
    position: relative;
    display: inline-block;
}
.dropdown-content{
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content>*{
 color: black;
 padding: 12px 6px;
text-decoration: none;
 display: block;
}

.dropdown:hover .dropdown-content{
    display: block;
}
.dropdown-content>*:hover{
    background-color: #ddd;
}
setTheme = () => {
    let element = document.getElementById('doc');
    // element.setAttribute('class','dark');
    element.classList.toggle('dark');
}

  render() {
    return (
      <div id='doc' class='light'>
        <h1>Hey</h1>
        <button id='btn' onClick={this.setTheme}>Click</button>
      </div>
    )
  }
import { useState, useEffect } from "react";

function getValue(key, initailValue) {
  const storedValue = JSON.parse(localStorage.getItem(key));
  if (storedValue) return storedValue;

  if (initailValue instanceof Function) return initailValue();
  return initailValue;
}

export default function useLocalStorage(key, initailValue) {
  const [value, setValue] = useState(() => {
    return getValue(key, initailValue);
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [value]);

  return [value, setValue];
}
import React from "react";

class Clock extends React.Component {
  constructor(props) {      //Constructor is  called when root is rendered
    super(props);
    this.state = { date: new Date() }; //intializes this.state with current time
  }


  componentDidMount() { //React lifecycle method, is been called when clock output is inserted in the DOM
    this.timerID = setInterval(
        () => this.tick(),
        1000
    )           //Here class component asks the browser to set up a timer to call the tick() method once a second
  }

  tick(){               
    this.setState({         //calling setState method with an object containing the current time
        date: new Date()
    });                     //setState method updates the current time
}

  componentWillUnmount() {      // Incase if clock component is ever removed from the DOM , react call this lifecycle method so the timer is stopped.
    clearInterval(this.timerID)
  }
  


  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

export default Clock;
import React from "react";

class Clock extends React.Component {
  constructor(props) {      //Constructor is  called when root is rendered
    super(props);
    this.state = { date: new Date() }; //intializes this.state with current time
  }


  componentDidMount() { //React lifecycle method, is been called when clock output is inserted in the DOM
    this.timerID = setInterval(
        () => this.tick(),
        1000
    )           //Here class component asks the browser to set up a timer to call the tick() method once a second
  }

  tick(){               
    this.setState({         //calling setState method with an object containing the current time
        date: new Date()
    });                     //setState method updates the current time
}

  componentWillUnmount() {      // Incase if clock component is ever removed from the DOM , react call this lifecycle method so the timer is stopped.
    clearInterval(this.timerID)
  }
  


  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

export default Clock;
import React from "react";

class Clock extends React.Component {
  constructor(props) {      //Constructor is  called when root is rendered
    super(props);
    this.state = { date: new Date() }; //intializes this.state with current time
  }


  componentDidMount() { //React lifecycle method, is been called when clock output is inserted in the DOM
    this.timerID = setInterval(
        () => this.tick(),
        1000
    )           //Here class component asks the browser to set up a timer to call the tick() method once a second
  }

  tick(){               
    this.setState({         //calling setState method with an object containing the current time
        date: new Date()
    });                     //setState method updates the current time
}

  componentWillUnmount() {      // Incase if clock component is ever removed from the DOM , react call this lifecycle method so the timer is stopped.
    clearInterval(this.timerID)
  }
  


  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

export default Clock;
import React from "react";

class Clock extends React.Component {
  constructor(props) {      //Constructor is  called when root is rendered
    super(props);
    this.state = { date: new Date() }; //intializes this.state with current time
  }


  componentDidMount() { //React lifecycle method, is been called when clock output is inserted in the DOM
    this.timerID = setInterval(
        () => this.tick(),
        1000
    )           //Here class component asks the browser to set up a timer to call the tick() method once a second
  }

  tick(){               
    this.setState({         //calling setState method with an object containing the current time
        date: new Date()
    });                     //setState method updates the current time
}

  componentWillUnmount() {      // Incase if clock component is ever removed from the DOM , react call this lifecycle method so the timer is stopped.
    clearInterval(this.timerID)
  }
  


  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

export default Clock;
import React from "react";

class Clock extends React.Component {
  constructor(props) {      //Constructor is  called when root is rendered
    super(props);
    this.state = { date: new Date() }; //intializes this.state with current time
  }


  componentDidMount() { //React lifecycle method, is been called when clock output is inserted in the DOM
    this.timerID = setInterval(
        () => this.tick(),
        1000
    )           //Here class component asks the browser to set up a timer to call the tick() method once a second
  }

  tick(){               
    this.setState({         //calling setState method with an object containing the current time
        date: new Date()
    });                     //setState method updates the current time
}

  componentWillUnmount() {      // Incase if clock component is ever removed from the DOM , react call this lifecycle method so the timer is stopped.
    clearInterval(this.timerID)
  }
  


  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

export default Clock;
import React from "react";

class Clock extends React.Component {
  constructor(props) {      //Constructor is  called when root is rendered
    super(props);
    this.state = { date: new Date() }; //intializes this.state with current time
  }


  componentDidMount() { //React lifecycle method, is been called when clock output is inserted in the DOM
    this.timerID = setInterval(
        () => this.tick(),
        1000
    )           //Here class component asks the browser to set up a timer to call the tick() method once a second
  }

  tick(){               
    this.setState({         //calling setState method with an object containing the current time
        date: new Date()
    });                     //setState method updates the current time
}

  componentWillUnmount() {      // Incase if clock component is ever removed from the DOM , react call this lifecycle method so the timer is stopped.
    clearInterval(this.timerID)
  }
  


  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

export default Clock;
import React from "react";

class Clock extends React.Component {
  constructor(props) {      //Constructor is  called when root is rendered
    super(props);
    this.state = { date: new Date() }; //intializes this.state with current time
  }


  componentDidMount() { //React lifecycle method, is been called when clock output is inserted in the DOM
    this.timerID = setInterval(
        () => this.tick(),
        1000
    )           //Here class component asks the browser to set up a timer to call the tick() method once a second
  }

  tick(){               
    this.setState({         //calling setState method with an object containing the current time
        date: new Date()
    });                     //setState method updates the current time
}

  componentWillUnmount() {      // Incase if clock component is ever removed from the DOM , react call this lifecycle method so the timer is stopped.
    clearInterval(this.timerID)
  }
  


  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

export default Clock;
npm install react-bootstrap bootstrap@5.1.3
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
import {useState} from 'react';

export default function App() {
  const initialState = [
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
  ];
  const [employees, setEmployees] = useState(initialState);

  const handleClick = () => {
    // 👇️ push object to end of state array
    setEmployees(current => [...current, {id: 3, name: 'Carl'}]);

    // 👇️ spread an array of objects into the state array
    // setEmployees(current => [
    //   ...current,
    //   ...[
    //     {id: 3, name: 'Carl'},
    //     {id: 4, name: 'Delilah'},
    //   ],
    // ]);

    // 👇️ push object to beginning of state array
    // setEmployees(current => [{id: 3, name: 'Zoey'}, ...current]);
  };

  return (
    <div>
      <div>
        <button onClick={handleClick}>Push to state array</button>
      </div>

      {employees.map((element, index) => {
        return (
          <div key={index}>
            <h2>{element.name}</h2>
          </div>
        );
      })}
    </div>
  );
}
import {useState} from 'react';

export default function App() {
  const [names, setNames] = useState(['Alice', 'Bob']);

  const handleClick = () => {
    // 👇️ push to end of state array
    setNames(current => [...current, 'Carl']);

    // 👇️ spread an array into the state array
    // setNames(current => [...current, ...['Carl', 'Delilah']]);

    // 👇️ push to beginning of state array
    // setNames(current => ['Zoey', ...current]);
  };

  return (
    <div>
      <div>
        <button onClick={handleClick}>Push to state array</button>
      </div>

      {names.map((element, index) => {
        return (
          <div key={index}>
            <h2>{element}</h2>
          </div>
        );
      })}
    </div>
  );
}
import React from "react"

export default function Card(props) {
    return (
        <div className="card">
      
      
      
            {props.openSpots === 0 && <div className="card--badge">SOLD OUT</div>} 
      		//if first statement is true, show last stetment/ otherwise dont
      
      
      
            <img src={`../images/${props.img}`} className="card--image" />
            <div className="card--stats">
                <img src="../images/star.png" className="card--star" />
                <span>{props.rating}</span>
                <span className="gray">({props.reviewCount}) • </span>
                <span className="gray">{props.location}</span>
            </div>
            <p className="card--title">{props.title}</p>
            <p className="card--price"><span className="bold">From ${props.price}</span> / person</p>
        </div>
    )
}
import React from "react"
import Navbar from "./components/Navbar"
import Hero from "./components/Hero"
import Card from "./components/Card"
import data from "./data"
/*
Challenge:

- import the array of data from data.js
- map over the array to create <Card /> components
- display the array of card components under the navbar
  (in place of the current <Card /> component)

Note: We haven't styled the group of components yet, so they'll
still be block elements, stacked vertically. We'll add styling later.
*/

export default function App() {
            // <Hero />
    const cards = data.map(item => {
        return (
            <Card 
                img={item.coverImg}
                rating={item.stats.rating}
                reviewCount={item.stats.reviewCount}
                location={item.location}
                title={item.title}
                price={item.price}
            />
        )
    })        
    
    return (
        <div>
            <Navbar />
            {cards}
        </div>
    )
}
function App() {
    const date = new Date()
    const hours = date.getHours()
    let timeOfDay
    
    if (hours < 12) {
        timeOfDay = "morning"
    } else if (hours >= 12 && hours < 17) {
        timeOfDay = "afternoon"
    } else {
        timeOfDay = "night"
    }
    return (
        <h1>Good {timeOfDay}!</h1>
    )
}
key={`${button.text}-${button.bootstrapWidth}-${i}`}
import React, { useState, useEffect } from 'react';
 
export default function PageTitle() {
  const [name, setName] = useState('');
 
 useEffect(() => {
    document.title = `Hi, ${name}`;
  }, [name]);
 
  return (
    <div>
      <p>Use {name} input field below to rename this page!</p>
      <input 
        onChange={({target}) => setName(target.value)} 
        value={name} 
        type='text' />
    </div>
  );
}

// now the entrry of great functional componentsw useEffect
const addMessage = (message) => {
  return {
    type: 'ADD',
    message: message
  }
};

const mapStateToProps = (state) => {
  return {
    messages: state
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    submitNewMessage: (message) => {
      dispatch(addMessage(message));
    }
  }
};

class Presentational extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h3>This is a Presentational Component</h3>
  }
};

const connect = ReactRedux.connect;
// change code below this line

const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps) (Presentational)
const addMessage = (message) => {
  return {
    type: 'ADD',
    message: message
  }
};

const mapStateToProps = (state) => {
  return {
    messages: state
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    submitNewMessage: (message) => {
      dispatch(addMessage(message));
    }
  }
};

class Presentational extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h3>This is a Presentational Component</h3>
  }
};

const connect = ReactRedux.connect;
// change code below this line

const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps) (Presentational)
const addMessage = (message) => {
  return {
    type: 'ADD',
    message: message
  }
};

const mapStateToProps = (state) => {
  return {
    messages: state
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    submitNewMessage: (message) => {
      dispatch(addMessage(message));
    }
  }
};

class Presentational extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h3>This is a Presentational Component</h3>
  }
};

const connect = ReactRedux.connect;
// change code below this line

const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps) (Presentational)
// package.json
"devDependencies": {
    "@typescript-eslint/eslint-plugin": "^5.11.0",
    "@typescript-eslint/parser": "^5.11.0",
    "eslint": "^8.8.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-import": "^2.25.4",
    "eslint-plugin-jest-dom": "^4.0.1",
    "eslint-plugin-jsx-a11y": "^6.5.1",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-react": "^7.28.0",
    "eslint-plugin-react-hooks": "^4.3.0",
    "eslint-plugin-simple-import-sort": "^7.0.0",
    "eslint-plugin-testing-library": "^5.0.5",
    "prettier": "^2.5.1"
  }

// .eslintrc.json
{
  "env": {
    "browser": true,
    "es2021": true,
    "jest": true
  },
  "extends": [
    "airbnb",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:testing-library/react",
    "plugin:jest-dom/recommended",
    "plugin:prettier/recommended"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module",
    "project": "tsconfig.json"
  },
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"],
        "paths": ["src"]
      }
    }
  },
  "plugins": [
    "react",
    "@typescript-eslint",
    "testing-library",
    "jest-dom",
    "simple-import-sort",
    "prettier"
  ],
  "rules": {
    "react/jsx-filename-extension": [1, { "extensions": [".tsx", ".jsx"] }],
    "testing-library/await-async-query": "error",
    "testing-library/no-await-sync-query": "error",
    "testing-library/prefer-user-event": "error",
    "testing-library/no-debugging-utils": "warn",
    "react/react-in-jsx-scope": "off",
    "import/extensions": ["error", "never"],
    "simple-import-sort/imports": "error",
    "simple-import-sort/exports": "error",
    "sort-imports": "off",
    "import/order": "off",
    "no-console": "warn",
    "@typescript-eslint/prefer-optional-chain": "warn",
    "@typescript-eslint/prefer-nullish-coalescing": "warn",
    "@typescript-eslint/no-for-in-array": "warn",
    "@typescript-eslint/prefer-for-of": "warn",
    "@typescript-eslint/no-floating-promises": "warn",
    "@typescript-eslint/promise-function-async": "warn",
    "@typescript-eslint/sort-type-union-intersection-members": "warn",
    "@typescript-eslint/no-unnecessary-boolean-literal-compare": "warn",
    "@typescript-eslint/no-confusing-non-null-assertion": "warn",
    "@typescript-eslint/no-non-null-asserted-nullish-coalescing": "warn",
    "@typescript-eslint/consistent-indexed-object-style": [
      "warn",
      "index-signature"
    ]
  }
}
// .vscode/settings.json
{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }
}
import {
  render as rtlRender,
  RenderOptions,
  RenderResult,
} from "@testing-library/react";
import { ReactElement } from "react";
import { Provider } from "react-redux";

import { configureStoreWithMiddlewares, RootState } from "../app/store";

type CustomRenderOptions = {
  preloadedState?: RootState;
  renderOptions?: Omit<RenderOptions, "wrapper">;
};

const render = (
  ui: ReactElement,
  { preloadedState = {}, ...renderOptions }: CustomRenderOptions = {}
): RenderResult => {
  const store = configureStoreWithMiddlewares(preloadedState);
  const Wrapper: React.FC = ({ children }) => {
    return <Provider store={store}>{children}</Provider>;
  };
  return rtlRender(ui, { wrapper: Wrapper, ...renderOptions });
};

export * from "@testing-library/react";
export { render };
module.exports = {
  presets: [["next/babel"]],
  plugins: [["import", { libraryName: "antd", style: true }]],
};
import type { AppProps } from "next/app";
import "styles/variables.less";
import "styles/style.sass";

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

export default MyApp;
@import "~antd/lib/style/themes/default.less";
@import "~antd/dist/antd.less"; // Import Ant Design styles

@primary-color: #10f5e2; // primary color for all components
@link-color: #10f5e2; // link color
@success-color: #60f7ca; // success state color
@warning-color: #faad14; // warning state color
@error-color: #f5222d; // error state color
@font-size-base: 14px; // major text font size
@heading-color: rgba(0, 0, 0, 0.85); // heading text color
@text-color: rgba(0, 0, 0, 0.65); // major text color
@text-color-secondary: rgba(0, 0, 0, 0.45); // secondary text color
@disabled-color: rgba(0, 0, 0, 0.25); // disable state color
@border-radius-base: 2px; // major border radius
@border-color-base: #d9d9d9; // major border color
@box-shadow-base: 0 3px 6px -4px rgba(0, 0, 0, 0.12),
  0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05); // major shadow for layers
/** @type {import('next').NextConfig} */
const withBundleAnalyzer = require("@next/bundle-analyzer")({
  enabled: process.env.ANALYZE === "true",
});

const withAntdLess = require("next-plugin-antd-less");

module.exports = withBundleAnalyzer(
  withAntdLess({
    // Or better still you can specify a path to a file
    lessVarsFilePath: "./styles/variables.less",
    // optional
    lessVarsFilePathAppendToEndOfContent: false,
    // optional https://github.com/webpack-contrib/css-loader#object
    cssLoaderOptions: {},

    // Other Config Here...

    webpack(config) {
      return config;
    },

    // ONLY for Next.js 10, if you use Next.js 11, delete this block
    future: {
      webpack5: true,
    },
    reactStrictMode: true
  })
);
// but answer becomes a string (not usable number)
number.toFixed(2)

// I don't know what parseFloat is - but this was the original answer i received, need to learn why its different than above
 parseFloat(portfolioValue * props.data.current_price).toFixed(2);
let coinNames = [
    "bitcoin",
    "ethereum",
    "stellar",
    "bitcoin-cash",
    "nucypher",
    "litecoin",
  ];
  coinNames = coinNames.map(function (coin) {
    return "%2C" + coin;
  });
React: 
className="text-muted"

html:
class="text-muted"
npx create-react-app haraj
npm set strict-ssl false
const codeMapping = {
    "01d": "CLEAR_DAY",
    "01n": "CLEAR_NIGHT",
    "02d": "PARTLY_CLOUDY_DAY",
    "02n": "PARTLY_CLOUDY_NIGHT",
    "03d": "CLOUDY",
    "03n": "CLOUDY",
    "04d": "RAIN",
    "04n": "RAIN",
    "09d": "RAIN",
    "09n": "RAIN",
    "10d": "SLEET",
    "10n": "SLEET",
    "11d": "SNOW",
    "13d": "SNOW",
    "13n": "SNOW",
    "50d": "FOG",
    "50n": "FOG",
  };
function formatFullDate() {
  let now = new Date();
  let allMonths = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ];
  let month = allMonths[now.getMonth()];
  let date = now.getDate();
  let year = now.getFullYear();
  return `${date} ${month} ${year}`;
  
  function formatDayAndTime() {
  let now = new Date();
  let allDays = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];
  let dayOfWeek = allDays[now.getDay()];
  let hour = ("0" + now.getHours()).slice(-2);
  let minutes = ("0" + now.getMinutes()).slice(-2);
  return `${dayOfWeek} ${hour}:${minutes}`;
}
import { useState } from "react";
import { useHistory } from "react-router-dom";

const Create = () => {
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const [author, setAuthor] = useState("mario");
  const [isLoading, setIsLoading] = useState(false);
  const history = useHistory();

  const handleSubmit = (e) => {
    e.preventDefault();
    const blog = { title, body, author };

    fetch("http://localhost:8000/blogs", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(blog),
    }).then(() => {
      setIsLoading(false);
      history.push("/");
    });
  };

  return (
    <div className="create">
      <h2>Add a New Blog</h2>
      <form onSubmit={handleSubmit}>
        <label>Blog title:</label>
        <input
          type="text"
          required
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
        <label>Blog body:</label>
        <textarea
          required
          value={body}
          onChange={(e) => setBody(e.target.value)}
        ></textarea>
        <label>Blog author:</label>
        <select value={author} onChange={(e) => setAuthor(e.target.value)}>
          <option value="mario">mario</option>
          <option value="yoshi">mario</option>
        </select>
        {!isLoading && <button>Add Blog</button>}
        {isLoading && <button disabled>Adding blog...</button>}
      </form>
    </div>
  );
};

export default Create;
const Form = () => {
  const [value, setValue] = useState("grapefruit");
  
  const handleChange = (event) => {
    setValue(event.target.value);
  }
  
   return (
  <form onSubmit={handleSubmit}>
    <label>
    Fav fruit
    	<select value={value} onChange={handleChange}>
          <option value="grapefruit">Grapefruit</option>
  		  <option value="apple">Apple</option>
  		</select>
  	</label>
  </form>
  )
 }
const App = () => {
  const [title, setTitle] = useState("default input");

  const handleSubmit = (event) => {
    event.preventDefault();

    const body = {
      title: title,
    };
    console.log(title);
  };

  return (
    <div className="container">
      <form onSubmit={handleSubmit}>
        <label htmlFor="title">Title</label>
        <input
          type="text"
          required
          id="title"
          value={title}
          onChange={(event) => {
            const value = event.target.value;
            setTitle(value);
          }}
        />
        <button>Submit</button>
      </form>
    </div>
  );
};
pagespeed on;

pagespeed FileCachePath "/var/cache/ngx_pagespeed/";

pagespeed FileCacheSizeKb 102400;

pagespeed FileCacheCleanIntervalMs 3600000;

pagespeed FileCacheInodeLimit 50000;

pagespeed EnableCachePurge on;

pagespeed PurgeMethod PURGE;

pagespeed RewriteLevel CoreFilters;

## Text / HTML
pagespeed EnableFilters combine_heads;
pagespeed EnableFilters collapse_whitespace;
pagespeed EnableFilters convert_meta_tags;
pagespeed EnableFilters elide_attributes;
pagespeed EnableFilters pedantic;
pagespeed EnableFilters remove_comments;
pagespeed EnableFilters remove_quotes;
pagespeed EnableFilters trim_urls;

## JavaScript
pagespeed EnableFilters combine_javascript;
pagespeed EnableFilters canonicalize_javascript_libraries;
pagespeed EnableFilters inline_javascript;

## CSS
pagespeed EnableFilters outline_css;
pagespeed EnableFilters combine_css;
pagespeed EnableFilters inline_import_to_link;
pagespeed EnableFilters inline_css;
pagespeed EnableFilters inline_google_font_css;
pagespeed EnableFilters move_css_above_scripts;
pagespeed EnableFilters move_css_to_head;
pagespeed EnableFilters prioritize_critical_css;
pagespeed EnableFilters rewrite_css;
pagespeed EnableFilters fallback_rewrite_css_urls;
pagespeed EnableFilters rewrite_style_attributes_with_url;

## Images
pagespeed EnableFilters dedup_inlined_images;
pagespeed EnableFilters inline_preview_images;
pagespeed EnableFilters resize_mobile_images;
pagespeed EnableFilters lazyload_images;
pagespeed EnableFilters inline_images;
pagespeed EnableFilters convert_gif_to_png;
pagespeed EnableFilters convert_jpeg_to_progressive;
pagespeed EnableFilters recompress_jpeg;
pagespeed EnableFilters recompress_png;
pagespeed EnableFilters recompress_webp;
pagespeed EnableFilters strip_image_color_profile;
pagespeed EnableFilters strip_image_meta_data;
pagespeed EnableFilters jpeg_subsampling;
pagespeed EnableFilters convert_png_to_jpeg;
pagespeed EnableFilters resize_images;
pagespeed EnableFilters resize_rendered_image_dimensions;
pagespeed EnableFilters convert_jpeg_to_webp;
pagespeed EnableFilters convert_to_webp_lossless;
pagespeed EnableFilters insert_image_dimensions;
pagespeed NoTransformOptimizedImages on;
pagespeed EnableFilters sprite_images;

pagespeed FetchHttps enable,allow_self_signed;

location ~ ".pagespeed.([a-z].)?[a-z]{2}.[^.]{10}.[^.]+" {
    add_header "" "";
}
location ~ "^/pagespeed_static/" { }
location ~ "^/ngx_pagespeed_beacon$" { }
location ~ "^/ngx_pagespeed_beacon$ps_dollar" { }
server {

listen 443;

…

include /etc/nginx/pagespeed.conf;
}
if (process.env.NODE_ENV == 'production') {
	config.plugins = [
		...config.plugins,
		new HtmlCriticalWebpackPlugin({
			base: path.resolve(__dirname, 'build'),
			src: 'index.html',
			dest: 'index.html',
			inline: true,
			minify: true,
			extract: true,
			width: 320,
			height: 565,
			penthouse: {
				blockJSRequests: false
			},
		})
	]
}
@font-face {
    font-family: 'Polo';
    src: url('external_assets/fonts/PoloR-Regular.eot');
    src: url('external_assets/fonts/PoloR-Regular.eot?#iefix') format('embedded-opentype'), url('external_assets/fonts/PoloR-Regular.woff2') format('woff2'), url('external_assets/fonts/PoloR-Regular.woff') format('woff'), url('external_assets/fonts/PoloR-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
    font-display: swap;
}
import React, { Suspense } from 'react';

const OtherComponent = React.lazy(() => import('./OtherComponent'));
// named chunk => AnotherComponent.<hash>.chunk.js
const AnotherComponent = React.lazy(() => import(/* webpackChunkName: "AnotherComponent" */ './AnotherComponent'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <section>
          <OtherComponent />
          <AnotherComponent />
        </section>
      </Suspense>
    </div>
  );
}
import gulp from 'gulp'
import imagemin from 'gulp-imagemin'
import optipng from 'imagemin-optipng'

gulp.task('optimize-png-images', () => {
	return gulp.src('./build/static/media/*.png')
		.pipe(imagemin([
			pngquant({
				quality: [0.2, 0.2],
				speed: 1
			})
		]))
		.pipe(gulp.dest('build/static/media/'))
})
import gulp from 'gulp'
import imagemin from 'gulp-imagemin'
import optipng from 'imagemin-optipng'

gulp.task('optimize-png-images', () => {
	return gulp.src('./build/static/media/*.png')
		.pipe(imagemin([
			optipng({optimizationLevel: 7})
		]))
		.pipe(gulp.dest('build/static/media/'))
})
server {
  listen  <port>
  brotli on;
  brotli_comp_level 7;
  brotli_types
  text/xml
  text/plain
  text/javascript
  text/css
  image/svg+xml
  image/x-icon
  image/x-win-bitmap
  image/vnd.microsoft.icon
  font/eot
  font/otf
  font/opentype
  application/x-font-opentype
  application/json
  application/x-font-ttf
  application/vnd.ms-fontobject
  application/javascript
  application/xml
  application/xhtml+xml
  application/x-javascript
  application/x-font-truetype
  application/xml+rss;
  ...
}
const CompressionPlugin = require('compression-webpack-plugin')
...
new CompressionPlugin({
	filename: '[path][base].br',
	algorithm: 'brotliCompress',
	test: /\.(js|css|html|svg)$/,
	compressionOptions: {
		level: 11
	},
	threshold: 10240,
	minRatio: 0.8
})
server {
  listen  <port>
  gzip on;
  gzip_vary on;
  gzip_proxied any;
  gzip_comp_level 6;
  gzip_types
  text/plain
  text/css
  text/xml
  application/json
  application/javascript
  application/xml+rss
  application/atom+xml
  application/xhtml+xml
  application/xml
  image/svg+xml;
  ...
}
const CompressionPlugin = require('compression-webpack-plugin')
...
new CompressionPlugin({
  filename: '[path][base].gz',
  algorithm: 'gzip',
  test: /\.js$|\.css$|\.html$/,
  threshold: 10240,
  minRatio: 0.8
})
import { useSelector, TypedUseSelectorHook } from "react-redux";
// Import type of state 
// Import {RootState} from '../store'

export const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector;
import React from "react";
import PropTypes from "prop-types";

const Header = ({ title }) => {
  return (
    <header className="header">
      <h1>{title}</h1>
    </header>
  );
};

Header.propTypes = {
  title: PropTypes.string.isRequired,
};

export default Header;


///// ----- USING IT -------
import Header from "./components/Header";
<Header title="New Pixar Movies" />
import React from "react";
import PropTypes from "prop-types";

const Table = ({ tableData, headingColumns, title, breakOn = "medium", onItemClick, onHeadingClick, headingColumnFields }) => {
  let tableClass = "table-container__table";

  if (breakOn === "small") {
    tableClass += " table-container__table--break-sm";
  } else if (breakOn === "medium") {
    tableClass += " table-container__table--break-md";
  } else if (breakOn === "large") {
    tableClass += " table-container__table--break-lg";
  }

  const data = tableData.map((row, index) => {
    let rowData = [];
    let i = 0;

    for (const key in row) {
      rowData.push({
        key: headingColumns[i],
        val: row[key],
      });
      i++;
    }

    return (
      <tr key={index} onClick={()=>onItemClick(index)}>
        {rowData.map((data, index) => (
          <td key={index} data-heading={data.key}>
            {data.val}
          </td>
        ))}
      </tr>
    );
  });

  return (
    <div className="table-container">
      <div className="table-container__title">
        <h2>{title}</h2>
      </div>
      <table className={tableClass}>
        <thead>
          <tr>
            {headingColumns.map((col, index) => (
              <th key={index}  onClick={() => onHeadingClick(headingColumnFields[index])}>{col}</th>
            ))}
          </tr>
        </thead>
        <tbody>{data}</tbody>
      </table>
    </div>
  );
};

Table.propTypes = {
  tableData: PropTypes.arrayOf(PropTypes.object).isRequired,
  headingColumns: PropTypes.arrayOf(PropTypes.string).isRequired,
  title: PropTypes.string.isRequired,
  breakOn: PropTypes.oneOf(["small", "medium", "large"]),
  onItemClick: PropTypes.func.isRequired,
  onHeadingClick: PropTypes.func.isRequired,
  headingColumnFields: PropTypes.arrayOf(PropTypes.string).isRequired
};

export default Table;



// ------ USING THE TABLE -------
import Table from "./components/Table";
        {data ? (
          <Table
            tableData={data.results.sort(sortMovies).map((movie) => {
              return [
                data.title,
                new Date(data.release_date).toLocaleDateString(
                  undefined,
                  options
                ),
              ];
            })}
            headingColumns={["Title", "Release Date"]}
            title="Pixar Movies"
            breakOn="small"
            onItemClick={handleClick}
            onHeadingClick={handleSort}
            headingColumnFields={["title", "release_date"]}
          />
        ) : null}
{
  "name": "frontend",
    // add proxy, so instead of looking at front end server, our api requests look at backend server
    // call it prox, then add the loopback address and the backend server port
  "proxy": "http://127.0.0.1:8080",
  "version": "0.1.0",
//Provider Component
import React, { Component } from 'react';

// Create new context
const MyContext = React.createContext();

// Create the Provider that will pass down state and methods to the rest of the application.
class MyProvider extends Component {
  state = {
    name: 'Dominic',
    age: 28,
  };
  render() {
    return (
      <MyContext.Provider value={{
        state: this.state,
        addYear: () => this.setState({
          age: this.state.age + 1
        })
      }}>
        {this.props.children}
      </MyContext.Provider>
    )
  }
}

// Create the consumer that will consume the data provided by the Provider.
class Company extends Component {
  render() {
    return(
      <div className="company">
        <MyContext.Consumer>
          {(context) => (
            //Fragment added here since you can only return one child
            <>
              <p>Welcome to {context.state.name}</p>
              <p>We are {context.state.age} years old!</p>
              <button onClick={context.addYear}>Add Year</button>
            </>
          )}
        </MyContext.Consumer>
      </div>
    )
  }
}

// We'll nest our Consumer inside another component just to show that we don't need to pass props to each component.
const Companies = () => (
  <div>
    <Company />
  </div>
)

class App extends Component {
  render() {
    return (
      // Ensure the provider wraps all the components you want to share data between.
      <MyProvider>
        <div className="App">
          <Companies />
        </div>
      </MyProvider>
    );
  }
}

export default App;
import React, { useState } from 'react'

const MyComponent = () => {
  const [toggle, setToggle] = useState(false)

  return(
    <>
      <button onClick={() => setToggle(!toggle)}>Toggle Dropdown Markup</button>
      {toggle && (
        <ul>
          <li>Show me</li>
          <li>Only when</li>
          <li>Toggle === true</li>
        </ul>
      )}
    </>
  )
}
//app.js
import React, { useState } from 'react';
import './App.css';

function App() {
  const [firstDieResult, setFirstDieResult] = useState(1);
  const [secondDieResult, setSecondDieResult] = useState(6);
  //OR
  //const [diceResult, setDiceResult] = useState({
  	//firstDieResult: 1,
  	//secondDieResult: 6,
	//});

  const firstDieImage = require(`./assets/${firstDieResult}.png`);
  const secondDieImage = require(`./assets/${secondDieResult}.png`);

  function rollDice() {
    setFirstDieResult(Math.floor(Math.random() * 6) + 1);
    setSecondDieResult(Math.floor(Math.random() * 6) + 1);
  }

  return (
    <div className="App">
      <header className="App-header">
        <div style={{ display: 'flex', margin: 20 }}>
          <img src={firstDieImage} className="die" alt="Die one" />
          <img src={secondDieImage} className="die" alt="Die two" />
        </div>
        <span>{firstDieResult + secondDieResult}</span>
        <button className="button" onClick={rollDice}>Roll</button>
      </header>
    </div>
  );
}

export default App;

//css

.App {
  text-align: center;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(16px + 2vmin);
  color: white;
}

.die {
  width: 50px;
  height: 50px;
  margin: 10px;
}

.button {
  margin-top: 20px;
  outline: none;
  animation: button-gradient 25s ease infinite;
  background-image: -webkit-linear-gradient(65deg,#21d4fd,#b721ff 50%,#017eff);
  background-image: linear-gradient(25deg,#21d4fd,#b721ff 50%,#017eff);
  background-size: 500%;
  border: none;
  border-radius: 3px;
  box-shadow: 0 3px 0 0 #5664a7;
  color: #fff;
  font-size: 14px;
  font-weight: 600;
  height: 40px;
  width: 150px;
}

.button:hover {
  box-shadow: 0 2px 0 0 #5664a7;
}

.button:active {
  box-shadow: inset 0 2px 4px rgba(0,0,0,0.25), 0 1px 2px rgba(0,0,0,0.05);
}
// get images => https://upmostly.com/wp-content/uploads/react-dice-assets.zip
import React, { useEffect, useState } from 'react';

function App() {
  const [age, setAge] = useState(0);
  
  updateAge(value) {
    setDisplayUsaStudents(
            (prevDisplayUsaStudents) => !prevDisplayUsaStudents
          );
    setAge({prevAge: value});
  };

  useEffect(() => {
    if (age !== 0 && age >= 21) {
      // Make API call to /beer
    } else {
      // Throw error 404, beer not found
    }
//the square parentheses with the age state variable inside is called the dependency array. //it tells the useEffect function to listen for any changes to the state of age.
//when age changes, useEffect executes
  }, [age]);

  return (
    <div>
      <p>Drinking Age Checker</p>
      <input
        type="number"
        value={age} 
        onChange={e => setAge(e.target.value)}
      />
    </div>
  );
}

export default App;
import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      age: 0,
    };
  }
  
  // this.checkAge is passed as the callback to setState
  updateAge = (value) => {
    this.setState({ age: value}, this.checkAge);
  };

  checkAge = () => {
    const { age } = this.state;
    if (age !== 0 && age >= 21) {
      // Make API call to /beer
    } else {
      // Throw error 404, beer not found
    }
  };

  render() {
    const { age } = this.state;
    return (
      <div>
        <p>Drinking Age Checker</p>
        <input
          type="number"
          value={age}
          onChange={e => this.updateAge(e.target.value)}
        />
      </div>
    );
  }

}

export default App;
//app.js
import React, { useState } from 'react';
import './App.css';
import Switch from "./Switch";

function App() {
  const [value, setValue] = useState(false);
  return (
    <div className="app">
      <Switch
        isOn={value}
        onColor="#EF476F"
        handleToggle={() => setValue(!value)}
      />
    </div>
  );
}

export default App;

//Switch.js
import React from 'react';

const Switch = ({ isOn, handleToggle, onColor }) => {
  return (
    <>
      <input
        checked={isOn}
        onChange={handleToggle}
        className="react-switch-checkbox"
        id={`react-switch-new`}
        type="checkbox"
      />
      <label
        style={{ background: isOn && onColor }}
        className="react-switch-label"
        htmlFor={`react-switch-new`}
      >
        <span className={`react-switch-button`} />
      </label>
    </>
  );
};

export default Switch;

//css
.react-switch-checkbox {
  height: 0;
  width: 0;
  visibility: hidden;
}

.react-switch-label {
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  width: 100px;
  height: 50px;
  background: grey;
  border-radius: 100px;
  position: relative;
  transition: background-color .2s;
}

.react-switch-label .react-switch-button {
  content: '';
  position: absolute;
  top: 2px;
  left: 2px;
  width: 45px;
  height: 45px;
  border-radius: 45px;
  transition: 0.2s;
  background: #fff;
  box-shadow: 0 0 2px 0 rgba(10, 10, 10, 0.29);
}

.react-switch-checkbox:checked + .react-switch-label .react-switch-button {
  left: calc(100% - 2px);
  transform: translateX(-100%);
}

.react-switch-label:active .react-switch-button {
  width: 60px;
}
import React from 'react';

const people = [
  {
    name: 'James',
    age: 31,
  },
  {
    name: 'John',
    age: 45,
  },
  {
    name: 'Paul',
    age: 65,
  },
  {
    name: 'Ringo',
    age: 49,
  },
  {
    name: 'George',
    age: 34,
  }
];

function App() {
  return (
    <div>
      {people.filter(person => person.age < 60).map(filteredPerson => (
        <li>
          {filteredPerson.name}
        </li>
      ))}
    </div>
  );
}

export default App;
import React from 'react';

const names = ['James', 'John', 'Paul', 'Ringo', 'George'];

function App() {
  return (
    <div>
      {names.filter(name => name.includes('J')).map(filteredName => (
        <li>
          {filteredName}
        </li>
      ))}
    </div>
  );
}

export default App;
function getFromLS(key) {
  let ls = {};
  if (global.localStorage) {
    try {
      ls = JSON.parse(global.localStorage.getItem('rgl-8')) || {};
    } catch (e) {}
  }
  return ls[key];
}
function saveToLS(key, value) {
  if (global.localStorage) {
    global.localStorage.setItem(
      'rgl-8',
      JSON.stringify({
        [key]: value,
      }),
    );
  }
}
const rootDomElement: any = document.getElementById('root');
const newBlock = (
      <div>
        <p>The New Content</>
      </div>
  );
ReactDOM.createPortal(newBlock, rootDomElement);


// you can return it too
// return ReactDOM.createPortal(PDFPopup, RootDomElement);
  def search
    baseurl = "https://api.themoviedb.org/3/discover/movie?api_key=#{ENV['REACT_APP_TMDB_API_KEY']}&language=en-						US&sort_by=popularity.desc&with_watch_monetization_types=flatrate&include_adult=false&include_video		=false&page=${moviePageIndex}";
    urladdon = params[:urlAddon]

    require 'uri'
    require 'net/http'

    uri = URI("#{baseurl}#{urladdon}")
    res = Net::HTTP.get_response(uri)

    if res.is_a?(Net::HTTPSuccess)
      render json: res.body
    else
      render json: res.body, status: :bad_request
    end
  end
  const getMovies = async (url) => {
    setError(null);
    try {
      const response = await fetch(url);

      if (!response.ok) {
        throw new Error("Something went wrong!");
      }

      const data = await response.json();
      
      if (data.results.length === 0) {
        throw new Error("Sorry, no movies were found.");
      }
      
      const transformedMovies = data.results.map((movie) => {
        return {
          id: movie.id,
          title: movie.title,
          description: movie.overview,
          rating: movie.vote_average,
          genres: movie.genre_ids,
          poster_path: movie.poster_path,
          backdrop_path: movie.backdrop_path,
          year: movie.release_date
        }
      })
      setTotalPages(data.total_pages);
      setMovies(transformedMovies);
      chooseMovie(transformedMovies);
    } catch (errorThrown) {
      setError(errorThrown.message);
    }
  }
star

Sat Mar 16 2024 23:38:29 GMT+0000 (Coordinated Universal Time) https://github.com/shadcn-ui/taxonomy/blob/main/app/(auth)/login/page.tsx

#react #react.js #javascript #jsx #tailwind #css
star

Sat Mar 09 2024 22:48:13 GMT+0000 (Coordinated Universal Time)

#geolocation #react
star

Sat Feb 17 2024 23:59:49 GMT+0000 (Coordinated Universal Time)

#react #context #provider #hook
star

Sat Feb 17 2024 23:27:13 GMT+0000 (Coordinated Universal Time)

#react #context #provider
star

Thu Feb 15 2024 22:04:22 GMT+0000 (Coordinated Universal Time)

#react #filter #query
star

Tue Oct 17 2023 10:33:44 GMT+0000 (Coordinated Universal Time)

#typescript #react #polymorphic
star

Wed Aug 30 2023 23:57:12 GMT+0000 (Coordinated Universal Time)

#react #usecontext #react.js
star

Wed Aug 23 2023 15:11:05 GMT+0000 (Coordinated Universal Time) https://youtu.be/Sgcfiow4fVQ?t=141

#vite #react
star

Sun Jul 23 2023 12:55:51 GMT+0000 (Coordinated Universal Time)

#react
star

Sun Jul 23 2023 11:06:04 GMT+0000 (Coordinated Universal Time)

#react
star

Mon Apr 17 2023 16:53:27 GMT+0000 (Coordinated Universal Time)

#spa #react #waiting
star

Tue Apr 04 2023 14:01:45 GMT+0000 (Coordinated Universal Time)

#d3 #react #meteor #3d #bar #antd
star

Fri Mar 17 2023 16:14:11 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/72117276/how-to-properly-use-fontawesome-on-react-js

#react #react.js #fontawosome
star

Sun Feb 26 2023 04:30:38 GMT+0000 (Coordinated Universal Time) https://dev.to/arafat4693/15-useful-react-custom-hooks-that-you-can-use-in-any-project-2ll8

#react #hooks
star

Wed Feb 22 2023 18:17:51 GMT+0000 (Coordinated Universal Time) https://blog.logrocket.com/type-html-faster-react-emmet-vs-code/

#emmet #vscode #react #react.js
star

Sun Oct 30 2022 23:09:44 GMT+0000 (Coordinated Universal Time)

#react #show #hide #substring #paragraph #content
star

Thu Oct 27 2022 12:40:10 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=kM73pwJpT1M

#react #antd #pagination
star

Tue Oct 25 2022 16:29:15 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=QkPJV9DonZ0&t=124s

#react #loader #loadejs #loadercss
star

Sun Oct 16 2022 05:13:57 GMT+0000 (Coordinated Universal Time)

#react #show #hide #substring #paragraph #content
star

Sat Oct 15 2022 23:34:47 GMT+0000 (Coordinated Universal Time)

#react #useeffect #mediaquery
star

Thu Oct 06 2022 05:49:42 GMT+0000 (Coordinated Universal Time)

#switch #react #ifs #javascript
star

Tue Sep 13 2022 18:26:55 GMT+0000 (Coordinated Universal Time)

#react
star

Tue Sep 13 2022 18:24:22 GMT+0000 (Coordinated Universal Time)

#react
star

Tue Sep 13 2022 18:23:17 GMT+0000 (Coordinated Universal Time)

#react
star

Fri Aug 12 2022 00:08:07 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/73327361/pass-usestate-function-as-props

#react
star

Thu Aug 11 2022 23:47:18 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Aug 04 2022 05:08:50 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_dropdown_hover

#javascript #react #css #button #hover #dropdown
star

Mon Aug 01 2022 09:37:29 GMT+0000 (Coordinated Universal Time)

#javascript #react
star

Sun Jul 24 2022 20:33:08 GMT+0000 (Coordinated Universal Time)

#react #localstorage #customhook
star

Fri Jul 22 2022 06:34:40 GMT+0000 (Coordinated Universal Time) https://reactjs.org/docs/state-and-lifecycle.html

#javascript #react
star

Fri Jul 22 2022 06:34:39 GMT+0000 (Coordinated Universal Time) https://reactjs.org/docs/state-and-lifecycle.html

#javascript #react
star

Fri Jul 22 2022 06:34:39 GMT+0000 (Coordinated Universal Time) https://reactjs.org/docs/state-and-lifecycle.html

#javascript #react
star

Fri Jul 22 2022 06:34:38 GMT+0000 (Coordinated Universal Time) https://reactjs.org/docs/state-and-lifecycle.html

#javascript #react
star

Fri Jul 22 2022 06:34:38 GMT+0000 (Coordinated Universal Time) https://reactjs.org/docs/state-and-lifecycle.html

#javascript #react
star

Fri Jul 22 2022 06:34:38 GMT+0000 (Coordinated Universal Time) https://reactjs.org/docs/state-and-lifecycle.html

#javascript #react
star

Fri Jul 22 2022 06:34:38 GMT+0000 (Coordinated Universal Time) https://reactjs.org/docs/state-and-lifecycle.html

#javascript #react
star

Mon Jul 18 2022 09:26:01 GMT+0000 (Coordinated Universal Time)

#react #javascript #bootstrap
star

Mon Jul 18 2022 06:26:01 GMT+0000 (Coordinated Universal Time)

#react #javascript
star

Thu Jul 14 2022 19:04:08 GMT+0000 (Coordinated Universal Time)

#react #javascript
star

Thu Jul 14 2022 19:02:07 GMT+0000 (Coordinated Universal Time)

#react #javascript
star

Thu Jul 14 2022 05:37:16 GMT+0000 (Coordinated Universal Time) https://react-tutorial.app/app.html?id

#react #javascript
star

Wed Apr 13 2022 11:00:23 GMT+0000 (Coordinated Universal Time)

#react #js
star

Wed Apr 13 2022 10:13:32 GMT+0000 (Coordinated Universal Time)

#react #js
star

Mon Apr 11 2022 11:27:43 GMT+0000 (Coordinated Universal Time)

#react #js
star

Wed Feb 23 2022 05:42:38 GMT+0000 (Coordinated Universal Time) https://www.codecademy.com/learn/react-102/modules/react-102-stateless-inherit-stateful-u/cheatsheet

#react
star

Sun Feb 20 2022 17:49:17 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/how-to-handle-multiple-input-field-in-react-form-with-a-single-function/

#react #form
star

Sun Feb 20 2022 17:47:47 GMT+0000 (Coordinated Universal Time) https://www.bezkoder.com/react-node-mongodb-auth/

#react #authentication
star

Sun Feb 20 2022 17:46:35 GMT+0000 (Coordinated Universal Time)

#react
star

Sun Feb 20 2022 17:43:30 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/snippets

#react
star

Sun Feb 20 2022 17:28:29 GMT+0000 (Coordinated Universal Time) https://egghead.io/q/react-storybook?access_state

#react #storybook
star

Sun Feb 20 2022 17:21:57 GMT+0000 (Coordinated Universal Time) https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet

#react #cheetshit #codecademy
star

Sun Feb 20 2022 17:16:47 GMT+0000 (Coordinated Universal Time) https://egghead.io/q/react?access_state

#react #redux
star

Sat Feb 19 2022 18:07:27 GMT+0000 (Coordinated Universal Time)

#redux #react
star

Sat Feb 19 2022 17:57:24 GMT+0000 (Coordinated Universal Time)

#redux #react
star

Sat Feb 19 2022 17:57:20 GMT+0000 (Coordinated Universal Time)

#redux #react
star

Sat Feb 19 2022 17:55:50 GMT+0000 (Coordinated Universal Time)

#redux #react
star

Sat Feb 19 2022 17:40:37 GMT+0000 (Coordinated Universal Time) https://www.pluralsight.com/guides/code-splitting-your-redux-application

#redux #react
star

Sat Feb 19 2022 17:39:40 GMT+0000 (Coordinated Universal Time) https://www.pluralsight.com/guides/code-splitting-your-redux-application

#redux #react
star

Sat Feb 19 2022 14:44:30 GMT+0000 (Coordinated Universal Time) https://programmingwithmosh.com/javascript/es6-classes-and-functional-components-in-under-30-minutes/

#react
star

Sat Feb 19 2022 13:20:01 GMT+0000 (Coordinated Universal Time) https://thesmartcoder.dev/awesome-react-hooks/

#react #hooks
star

Sat Feb 19 2022 13:18:37 GMT+0000 (Coordinated Universal Time) https://egghead.io/courses/react-class-component-patterns

#react
star

Sat Feb 19 2022 13:17:17 GMT+0000 (Coordinated Universal Time) https://egghead.io/lessons/react-introduction-to-refactoring-a-react-application-to-react-hooks

#react #hooks
star

Sat Feb 19 2022 13:06:14 GMT+0000 (Coordinated Universal Time) https://whoisryosuke.com/blog/2020/handling-scroll-based-animations-in-react/

#react #animaton
star

Sat Feb 19 2022 13:04:13 GMT+0000 (Coordinated Universal Time) https://javascript.plainenglish.io/animate-when-element-is-in-view-with-framer-motion-63b254403bf

#react #animation
star

Sat Feb 19 2022 13:02:25 GMT+0000 (Coordinated Universal Time) https://blog.bitsrc.io/improve-react-performance-using-lazy-loading-and-suspense-933903171954

#react #testing #performance
star

Fri Feb 18 2022 19:10:18 GMT+0000 (Coordinated Universal Time) https://programmingwithmosh.com/javascript/create-modal-using-react/

#react #modal #component
star

Fri Feb 18 2022 19:08:20 GMT+0000 (Coordinated Universal Time) https://thesmartcoder.dev/awesome-react-hooks/

#react #hook
star

Fri Feb 18 2022 19:07:02 GMT+0000 (Coordinated Universal Time) https://www.pluralsight.com/guides/code-splitting-your-redux-application

#react #code
star

Fri Feb 18 2022 19:05:37 GMT+0000 (Coordinated Universal Time) https://upmostly.com/tutorials/react-background-image

#react #ui #backgroundimage
star

Fri Feb 18 2022 19:03:13 GMT+0000 (Coordinated Universal Time) https://usehooks-ts.com/

#react #hook
star

Fri Feb 18 2022 19:02:08 GMT+0000 (Coordinated Universal Time) https://thesmartcoder.dev/awesome-react-hooks/

#react #hook
star

Fri Feb 18 2022 18:55:01 GMT+0000 (Coordinated Universal Time) https://react-hooks-cheatsheet.com/

#react #usehooks
star

Fri Feb 18 2022 18:53:06 GMT+0000 (Coordinated Universal Time) https://usehooks-ts.com/

#usehooks #typescript #react
star

Thu Feb 17 2022 04:21:17 GMT+0000 (Coordinated Universal Time) https://flaviocopes.com/react-native-fix-iphoneos-cannot-be-located/

#react #ios
star

Fri Feb 04 2022 14:36:28 GMT+0000 (Coordinated Universal Time)

#react #typescript #react-testing-library
star

Tue Feb 01 2022 02:43:59 GMT+0000 (Coordinated Universal Time) https://kentcdodds.com/blog/how-to-use-react-context-effectively

#react #context
star

Thu Nov 25 2021 07:02:31 GMT+0000 (Coordinated Universal Time)

#typescript #react
star

Thu Nov 25 2021 07:00:42 GMT+0000 (Coordinated Universal Time)

#typescript #react
star

Thu Nov 25 2021 06:56:02 GMT+0000 (Coordinated Universal Time)

#typescript #react #css
star

Thu Nov 25 2021 06:52:52 GMT+0000 (Coordinated Universal Time)

#typescript #react
star

Wed Nov 10 2021 13:56:01 GMT+0000 (Coordinated Universal Time)

#react #javascript
star

Sun Nov 07 2021 11:44:44 GMT+0000 (Coordinated Universal Time)

#react #javascript
star

Wed Nov 03 2021 08:31:00 GMT+0000 (Coordinated Universal Time)

#react #html
star

Mon Nov 01 2021 11:17:17 GMT+0000 (Coordinated Universal Time)

#react
star

Sun Oct 31 2021 16:53:11 GMT+0000 (Coordinated Universal Time)

#react
star

Sun Oct 31 2021 13:26:36 GMT+0000 (Coordinated Universal Time)

#react #javascript
star

Fri Oct 08 2021 04:10:36 GMT+0000 (Coordinated Universal Time)

#javascript #react
star

Thu Oct 07 2021 22:47:06 GMT+0000 (Coordinated Universal Time)

#javascript #react
star

Thu Oct 07 2021 21:49:01 GMT+0000 (Coordinated Universal Time)

#javascript #react
star

Thu Oct 07 2021 09:06:04 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Oct 07 2021 09:05:18 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Oct 07 2021 09:01:24 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Oct 07 2021 09:00:53 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Oct 07 2021 08:59:14 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Oct 07 2021 08:58:45 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Oct 07 2021 08:58:05 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Oct 07 2021 08:53:20 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Oct 07 2021 08:52:00 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Oct 07 2021 08:51:10 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Oct 07 2021 08:49:21 GMT+0000 (Coordinated Universal Time)

#react
star

Thu Jul 29 2021 20:28:06 GMT+0000 (Coordinated Universal Time)

#javascript #react #table
star

Thu Jul 29 2021 20:26:18 GMT+0000 (Coordinated Universal Time)

#javascript #react #table
star

Sat Jul 24 2021 21:07:28 GMT+0000 (Coordinated Universal Time) https://dev.to/bharati21/javascript-loading-techniques-performance-56lp

#react
star

Sat Jul 24 2021 11:38:30 GMT+0000 (Coordinated Universal Time) https://www.bezkoder.com/react-hooks-jwt-auth/

#react #jwt
star

Fri Jul 23 2021 09:34:36 GMT+0000 (Coordinated Universal Time) https://reactchartjs.github.io/react-chartjs-2/

#chart #react
star

Tue Jun 29 2021 10:17:43 GMT+0000 (Coordinated Universal Time)

#react.js #javascript #react
star

Tue Jun 29 2021 10:10:50 GMT+0000 (Coordinated Universal Time) https://dommagnifi.co/2020-12-03-toggle-state-with-react-hooks/

#react.js #javascript #react #usestate #setstate
star

Tue Jun 29 2021 10:09:25 GMT+0000 (Coordinated Universal Time)

#react.js #javascript #react #usestate #setstate
star

Tue Jun 29 2021 10:03:32 GMT+0000 (Coordinated Universal Time)

#react.js #javascript #react #usestate
star

Tue Jun 29 2021 09:50:41 GMT+0000 (Coordinated Universal Time)

#react.js #javascript #react
star

Tue Jun 29 2021 09:45:03 GMT+0000 (Coordinated Universal Time) https://upmostly.com/tutorials/build-a-react-switch-toggle-component

#react.js #javascript #react
star

Tue Jun 29 2021 09:34:54 GMT+0000 (Coordinated Universal Time) https://upmostly.com/tutorials/react-filter-filtering-arrays-in-react-with-examples

#array #react.js #javascript #react #filter #map
star

Tue Jun 29 2021 09:30:58 GMT+0000 (Coordinated Universal Time)

#array #react.js #javascript #react #filter #map
star

Wed Jun 09 2021 18:44:37 GMT+0000 (Coordinated Universal Time) https://javascript.plainenglish.io/tired-of-boring-static-dashboards-lets-build-a-fully-customizable-dashboard-in-react-88cb5369cfe1

#react
star

Wed Jun 09 2021 14:49:41 GMT+0000 (Coordinated Universal Time) https://javascript.plainenglish.io/tired-of-boring-static-dashboards-lets-build-a-fully-customizable-dashboard-in-react-88cb5369cfe1

#react #react.js #draggable
star

Tue May 25 2021 08:03:23 GMT+0000 (Coordinated Universal Time)

#react #portal #reactportal
star

Mon May 24 2021 18:07:47 GMT+0000 (Coordinated Universal Time)

#react #api #ruby #rubyonrails
star

Mon May 24 2021 17:37:55 GMT+0000 (Coordinated Universal Time)

#react #api #fetch #async #error
star

Fri Apr 23 2021 17:12:19 GMT+0000 (Coordinated Universal Time) https://codesandbox.io/s/rmmzrkm75o?file

#react
star

Fri Apr 23 2021 17:12:01 GMT+0000 (Coordinated Universal Time) https://recharts.org/en-US/

#react
star

Sat Mar 07 2020 21:45:45 GMT+0000 (Coordinated Universal Time) https://dev.to/m0nica/automating-file-creation-with-javascript-8j5

#commandline #javascript #tutorial #react

Save snippets that work with our extensions

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