Snippets Collections
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

Tue Sep 13 2022 18:26:55 GMT+0000 (UTC)

#react
star

Tue Sep 13 2022 18:24:22 GMT+0000 (UTC)

#react
star

Tue Sep 13 2022 18:23:17 GMT+0000 (UTC)

#react
star

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

#react
star

Thu Aug 11 2022 23:47:18 GMT+0000 (UTC)

#react
star

Thu Aug 04 2022 05:08:50 GMT+0000 (UTC) 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 (UTC)

#javascript #react
star

Sun Jul 24 2022 20:33:08 GMT+0000 (UTC)

#react #localstorage #customhook
star

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

#javascript #react
star

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

#javascript #react
star

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

#javascript #react
star

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

#javascript #react
star

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

#javascript #react
star

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

#javascript #react
star

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

#javascript #react
star

Mon Jul 18 2022 09:26:01 GMT+0000 (UTC)

#react #javascript #bootstrap
star

Mon Jul 18 2022 06:26:01 GMT+0000 (UTC)

#react #javascript
star

Thu Jul 14 2022 19:04:08 GMT+0000 (UTC)

#react #javascript
star

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

#react #javascript
star

Wed Apr 13 2022 11:00:23 GMT+0000 (UTC)

#react #js
star

Wed Apr 13 2022 10:13:32 GMT+0000 (UTC)

#react #js
star

Mon Apr 11 2022 11:27:43 GMT+0000 (UTC)

#react #js
star

Wed Feb 23 2022 05:42:38 GMT+0000 (UTC) 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 (UTC) 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 (UTC) https://www.bezkoder.com/react-node-mongodb-auth/

#react #authentication
star

Sun Feb 20 2022 17:46:35 GMT+0000 (UTC)

#react
star

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

#react
star

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

#react #storybook
star

Sun Feb 20 2022 17:21:57 GMT+0000 (UTC) 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 (UTC) https://egghead.io/q/react?access_state

#react #redux
star

Sat Feb 19 2022 18:07:27 GMT+0000 (UTC)

#redux #react
star

Sat Feb 19 2022 17:57:24 GMT+0000 (UTC)

#redux #react
star

Sat Feb 19 2022 17:57:20 GMT+0000 (UTC)

#redux #react
star

Sat Feb 19 2022 17:55:50 GMT+0000 (UTC)

#redux #react
star

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

#redux #react
star

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

#redux #react
star

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

#react
star

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

#react #hooks
star

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

#react
star

Sat Feb 19 2022 13:17:17 GMT+0000 (UTC) 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 (UTC) https://whoisryosuke.com/blog/2020/handling-scroll-based-animations-in-react/

#react #animaton
star

Sat Feb 19 2022 13:04:13 GMT+0000 (UTC) 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 (UTC) 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 (UTC) https://programmingwithmosh.com/javascript/create-modal-using-react/

#react #modal #component
star

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

#react #hook
star

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

#react #code
star

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

#react #ui #backgroundimage
star

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

#react #hook
star

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

#react #hook
star

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

#react #usehooks
star

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

#usehooks #typescript #react
star

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

#react #ios
star

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

#react #context
star

Thu Nov 25 2021 07:02:31 GMT+0000 (UTC)

#typescript #react
star

Thu Nov 25 2021 07:00:42 GMT+0000 (UTC)

#typescript #react
star

Thu Nov 25 2021 06:56:02 GMT+0000 (UTC)

#typescript #react #css
star

Thu Nov 25 2021 06:52:52 GMT+0000 (UTC)

#typescript #react
star

Wed Nov 10 2021 13:56:01 GMT+0000 (UTC)

#react #javascript
star

Wed Nov 03 2021 08:31:00 GMT+0000 (UTC)

#react #html
star

Mon Nov 01 2021 11:17:17 GMT+0000 (UTC)

#react
star

Sun Oct 31 2021 16:53:11 GMT+0000 (UTC)

#react
star

Thu Oct 07 2021 22:47:06 GMT+0000 (UTC)

#javascript #react
star

Thu Oct 07 2021 21:49:01 GMT+0000 (UTC)

#javascript #react
star

Thu Oct 07 2021 09:06:04 GMT+0000 (UTC)

#react
star

Thu Oct 07 2021 09:05:18 GMT+0000 (UTC)

#react
star

Thu Oct 07 2021 09:01:24 GMT+0000 (UTC)

#react
star

Thu Oct 07 2021 09:00:53 GMT+0000 (UTC)

#react
star

Thu Oct 07 2021 08:59:14 GMT+0000 (UTC)

#react
star

Thu Oct 07 2021 08:58:45 GMT+0000 (UTC)

#react
star

Thu Oct 07 2021 08:58:05 GMT+0000 (UTC)

#react
star

Thu Oct 07 2021 08:53:20 GMT+0000 (UTC)

#react
star

Thu Oct 07 2021 08:52:00 GMT+0000 (UTC)

#react
star

Thu Oct 07 2021 08:51:10 GMT+0000 (UTC)

#react
star

Thu Oct 07 2021 08:49:21 GMT+0000 (UTC)

#react
star

Thu Jul 29 2021 20:28:06 GMT+0000 (UTC)

#javascript #react #table
star

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

#react
star

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

#react #jwt
star

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

#chart #react
star

Tue Jun 29 2021 10:17:43 GMT+0000 (UTC)

#react.js #javascript #react
star

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

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

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

#react.js #javascript #react
star

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

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

Wed Jun 09 2021 18:44:37 GMT+0000 (UTC) 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 (UTC) 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 (UTC)

#react #portal #reactportal
star

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

#react
star

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

#react
star

Sat Mar 07 2020 21:45:45 GMT+0000 (UTC) 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