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

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