Skip to content

Instantly share code, notes, and snippets.

@nurmdrafi
Last active August 17, 2022 13:50
Show Gist options
  • Select an option

  • Save nurmdrafi/6efae94589f8423a5c4ad1fcd97dabfa to your computer and use it in GitHub Desktop.

Select an option

Save nurmdrafi/6efae94589f8423a5c4ad1fcd97dabfa to your computer and use it in GitHub Desktop.

Scroll To Top Button

import React, { useState } from "react";
import { HashLink } from "react-router-hash-link";
import { BsArrowUp } from "react-icons/bs";

const ScrollToTop = () => {
  const [visible, setVisible] = useState(false);

  const toggleVisible = () => {
    let scrolled = window.pageYOffset;
    if (scrolled > 500) {
      setVisible(true);
    } else if (scrolled <= 500) {
      setVisible(false);
    }
  };

  window.addEventListener("scroll", toggleVisible);

  return (
    <div
      className={`sticky left-[90%] bottom-[20%] z-[1000]  ${
        visible ? "inline" : "hidden"
      }`}
    >
      <HashLink to="/#top">
        <BsArrowUp className="absolute h-10 w-10 animate-bounce text-black" />
      </HashLink>
    </div>
  );
};

export default ScrollToTop;

Create Dynamic Element Using Fragment

  const MenuItems = (
    <>
      <li>
        <Link to="/home">Home</Link>
      </li>
      <li>
        <Link to="/about">About</Link>
      </li>
      <li>
        <Link to="/appointment">Appointment</Link>
      </li>
      <li>
        <Link to="/reviews">Reviews</Link>
      </li>
      <li>
        <Link className="whitespace-nowrap" to="/contact">
          Contact Us
        </Link>
      </li>
      {!user && (
        <li>
          <Link to="/login">Login</Link>
        </li>
      )}
    </>

Conditional Style Using Object Value

const data = [{ status: active, status: passive }];

const Show = () => {
  return (
    <div>
      <span className={`cellWithStatus ${data.status}`}></span>
    </div>
  );
};
.cellWithStatus {
  &.active {
    color: red;
    background-color: red; // to > rgba()
  }
  &.passive {
    color: goldenrod;
    background-color: goldenrod; // to > rgba()
  }
}

Preview Uploaded Image

const [file, setFile] = useState("");

< onClick(e => setFile(e.target.files[0]))></ button>
<img src={file ? URL.createObjectURL(file) : "default image url"}/>

Conditional Rendering Using Switch statement

// Home
<div className="widgets">
  /* Similar in look different in data, here, 4 types Widget components exists.
  Inside Widget component set data object by using switch method based on type.
  */
  <Widget type="user" />
  <Widget type="order" />
  <Widget type="earnings" />
  <Widget type="balance" />
</div>
// Widgets
const Widget = ({ type }) => {
  let data;

  // temporary
  const amount = 100;
  const percentage = 20;
  // Switch
  switch (type) {
    case "user":
      data = {
        title: "USERS",
        isMoney: false,
        icon: <AiOutlineUser />,
      };
      break;
    case "order":
      data = {
        title: "ORDERS",
        isMoney: false,
        icon: <AiOutlineShopping />,
      };
      break;
    case "earnings":
      data = {
        title: "EARNINGS",
        isMoney: true,
        icon: <RiMoneyDollarCircleLine />,
      };
      break;
    case "balance":
      data = {
        title: "BALANCE",
        isMoney: true,
        icon: <MdOutlineAccountBalanceWallet />,
      };
      break;
    default:
      break;
  }
  return (
    <div className="widget">
      <div className="left">
        <span className="title">{data.title}</span>
        <span className="counter">
          {data.isMoney && "$"}
          {amount}
        </span>
      </div>

      <div className="right">
        <div className="percentage positive">
          <IoIosArrowUp />
          {percentage} %
        </div>
        {data.icon}
      </div>
    </div>
  );
};

export default Widget;

Search Functionality

import React, { useEffect, useState } from "react";

const UsersList = () => {
  const [users, setUsers] = useState([]);
  const [term, setTerm] = useState("");
  useEffect(() => {
    const fetchUser = async () => {
      const res = await fetch("https://jsonplaceholder.typicode.com/users");
      const data = await res.json();
      setUsers(data);
      console.log(users);
    };
    fetchUser();
  }, []);

  let renderUsers = users.map((user) => <h2>{user.name}</h2>);

  let filterUsers = users
    .filter(({ name }) => {
      return name.toLowerCase().indexOf(term) >= 0;
    })
    .map((user) => <h2 key={user.id}>{user.name}</h2>);
  return (
    <div>
      <input
        type="text"
        value={term}
        onChange={(e) => setTerm(e.target.value)}
      />
      {filterUsers}
    </div>
  );
};
export default UsersList;

Setup Background Image

const BannerBackground = {
    background: `url(${BannerImg})`,
    minHeight: "90vh",
    backgroundRepeat: "no-repeat",
    backgroundPosition: "center left",
    boxShadow: "25px 25px 50px 0 #F6F7F9 inset, -25px -25px 50px 0 #F6F7F9 inset" // blur border edge
  };
OR
import BannerImg from "../image/banner.png";

<div style={{backgroundImage: `url(${BannerImg})`}}></div>

Conditionally Disable Button

<PrimaryButton disabled={service.slots.length === 0}>
            Book Appointment
</PrimaryButton>
// Button Component
const PrimaryButton = ({ children, ...props }) => {
  return (
    <button
      disabled={props.disabled}
      className="btn btn-primary uppercase font-bold text-white my-6">
      {children}
    </button>
  );
};

export default PrimaryButton;

React-Leaflet

import { MapContainer, Marker, Popup, TileLayer } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import icon from "leaflet/dist/images/marker-icon.png";
import L from "leaflet";
import iconShadow from "leaflet/dist/images/marker-shadow.png";

let DefaultIcon = L.icon({
  iconUrl: icon,
  shadowUrl: iconShadow,
});

L.Marker.prototype.options.icon = DefaultIcon;

<section className="container-fluid p-0">
  <MapContainer center={[23.7934, 90.4064]} zoom={16} scrollWheelZoom={false}>
    <TileLayer
      attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
    <Marker position={[23.7934, 90.4064]}>
      <Popup>My Location</Popup>
    </Marker>
  </MapContainer>
</section>;
// css
.leaflet-container{
  height: 500px !important;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment