Skip to content

Code snippets to help grasp the concepts of the web.

Notifications You must be signed in to change notification settings

TommieNg/tommie-snippets

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

98 Commits
 
 
 
 
 
 

Repository files navigation

Tommie's code snippets

A repository to run code snippets.


Index


Stack


Summary

Topic Programming Language Description Links
static keyword JavaScript Using the JS static keyword in OOP classes Twitter post and Raw code
Promises JavaScript Two different ways to call API endpoints Twitter post and Raw code
Promises JavaScript Promise chaining and .then keyword Twitter post and Raw code
Promises JavaScript Async await syntactic sugar Twitter post and Raw code
Promise.all JavaScript Run multiple promises in parallel, and wait for all of them to finish Twitter post and Raw code
Rejecting a promise JavaScript Rejecting a promise if we have a network error, or a problem with the data we fetch from the server Twitter post and Raw code
try...catch...finally JavaScript Executing code using the catch or finally block Twitter post and Raw code
Promises JavaScript What is a Promise? Twitter post and Raw code
String method split JavaScript Split a string into an array of strings Twitter post and Raw code
Type function arguments TypeScript Typing your function arguments Twitter post and Raw code
Creating DOM nodes HTML, JavaScript Creating and appending DOM nodes in HTML with JavaScript Twitter post and Raw code
Intro to React API HTML, JavaScript, React Creating an element using the React API Twitter post and Raw code
Intro to JSX HTML, JavaScript, React Using JSX instead of the React API Twitter post and Raw code
Intro to JSDoc JavaScript Documenting complex functions with JSDoc Twitter post and Raw code
The Map object JavaScript Learning about the Map object and its key-value pairs Twitter post and Raw code
Built-in types and primitives TypeScript Introduction to TypeScript Twitter post and Raw code
Interfaces TypeScript Making your own custom types with Interfaces Twitter post and Raw code
Generics TypeScript Generics Twitter post and Raw code
Define custom types with type aliases TypeScript Another way of creating custom types Twitter post and Raw code
Enums TypeScript Enums, or enumerable types, are a special kind of type that holds a list of hardcoded values. Once you define an enum, you can refer to it like any other regular type. Twitter post and Raw code
Typing your functions TypeScript Previously, we learned on applying type information to variables. Functions are also an important part of JavaScript development, so let's learn how to type them too! Twitter post and Raw code
Generics (reviewed) TypeScript A generic type is a representation of any type that you’ll substitute in. Twitter post and Raw code
Generics constraints TypeScript Another feature of generics are their constraints, which lets you add more restrictions on the types that can be used as parameters in your functions. Twitter post and Raw code
Spreading attributes HTML, JavaScript, React Spreading props/attributes in React Twitter post and Raw code
Custom components HTML, JavaScript, React Creating JSX custom components Twitter post and Raw code
Prop types HTML, JavaScript, React Typechecking with prop-types Twitter post and Raw code
React fragments HTML, JavaScript, React Using React fragments Twitter post and Raw code
Intro to React styling React, CSS Primary way to style in React Twitter post and Raw code
React custom styling React, CSS Styling with custom components and props Twitter post and Raw code
React form - Intro React Introduction to React forms Twitter post and Raw code
React form - useRef React Getting a value from an input with a ref Twitter post and Raw code
React key prop React Keeping track of an element with the key prop Twitter post and Raw code
useState React The useState hook Twitter post and Raw code
useState (continued) React Example from the Twitter thread on the hook Twitter thread and Raw code
useState — passing an initial state prop React Here's a way to make our Toggle component accept an initialState prop. Then, we can initialize our state with that value. Twitter post and Raw code
useEffect — Introduction React The useEffect hook allows you to execute some code after React finishes rendering, or re-rendering the component to the DOM. It accepts a callback function as an argument, which will be called by React after the DOM has finished updating. Twitter post and Raw code
useState — Lazy initial state React The useState hook will also let you pass an anonymous function, so that the hook can only call that anonymous function to get the value from the state, only when your component is being rendered for the first time in your app. Twitter post and Raw code
useEffect — the dependency array React useEffect lets you pass a second argument, which is the dependency array. This tells React that the callback function in your useEffect should only be called when the dependencies changed. Twitter post and Raw code
Custom hook — useState with localStorage React In JavaScript, you'd store your reusable logic in functions. In React, if some logic inside a component can be reused in other components, you'd create what we call a custom hook! Twitter post and Raw code
Lifting state up React How to share state between sibling components? Lift it up 🏋️‍♀️ Find a lowest common parent shared between the components and add the state management there. Then, pass the state and a way to update that state down in the needed components. Twitter post and Raw code
CSS modules React "By creating a CSS file with the .module.css extension, you'll have created a module where you can't access the classes without importing. To use the class name, you can default import the "classes" object from the .module.css file, and then use the JSX expression {classes.[insertYourCSSClassHere]} to use the styling! It prevents classes with the same name from overlapping with each other by using name mangling." — Khanh Twitter post and Raw code
State colocation React A week ago, we talked about how to lift state up in React. Today, let's discuss pushing state down, or colocating state! I like how educator Kent C. Dodds describes it: "Place code as close to where it's relevant as possible". Twitter post and Raw code
Integrating UI libraries that works directly with the DOM React Some UI libraries work with the DOM directly. In JSX, <div>hi</div> is syntactic sugar for React.createElement("div", null, "hi"). We don't have access to DOM nodes in our function component. DOM nodes aren't created at all until the ReactDOM.render method is called. Functional components are responsible for creating our React elements and it’s bad practice to interact directly with the DOM in React. To access the DOM, ask React to give you access to a DOM node when it renders your component. This happens with the prop named ref. Twitter post and Raw code
HTTP requests React When building apps, you’ll find yourself needing another kind of side-effect: API calls, or HTTP requests. This is pretty similar to our previous example of side-effects in interacting with the DOM, or using APIs like localStorage. What those have in common is that they all work with the useEffect hook. I personally found it simpler to use the Promise-based .then statement rather than using the async/await syntax, but it's really up to you how you'd rather do it. Twitter post and Raw code
HTTP requests — handling errors React Mistakes inevitably happen and errors will need handling so users don't get confounded. When handling Promise errors, there are different options like using the .catch statement or using the second argument of the Promised-based .then statement. When using the .catch statement, you handle errors in the Promise. However, you also handle an error in the setWinners(data) call, because of our Promises work. When using the second argument of the .then statement, you catch errors that happens in the fetch only. In our example, I thought calling setWinners would not throw an error because React handles it, so I tried the second argument way of doing it. Twitter post and Raw code
HTTP requests status React Help your user understand the state of your application by implementing a status state for your API call. By adding a state to represent the status of our components' explicitly, you won't have to worry about what state you might get, and how to show it for a particular case, and when to set or not set it for other use cases. Here are examples of possible states we can work with: idle: No request has been sent., ending: Started request, resolved: Successful request., rejected: Failed request. Twitter post and Raw code
Putting your HTTP request state in an object React In the previous snippet, you might've noticed that a bunch of different setStates are called simultaneously, which would not be an issue, because React 17 and lower can batch all those calls together, but not when they’re async. 😅 The good news is that, since React 18, the batching for asynchronous automatic batching is available. Even though that new feature is available, it’s better to group those related states together in an object instead of creating individual different states. P.S.: I removed the error state just for the sake of readability. Twitter post and Raw code
Error Boundaries React We managed to catch errors if there happens to be one in our HTTP request, huzzah! Unfortunately, there are many other errors that might happen in applications. 🙁 You try handling those errors, but your app won’t always behave, and decides to go wild unleashing errors like a Pandora’s box. 📦 If your app throws an error and you don’t handle it, your app will be removed from the web page, and your user will be left will a blank screen. 😬 Twitter post and Raw code
Intro to the useReducer hook React When using the useState hook, you can manage the state in your app. However, there might be times where you might want to separate the state's logic from the components that make the state's changes. With many parts of the state that change simultaneously, an object with those parts of the state inside can help make it more organized. That’s where useReducer can be of help. 💡 Normally, the useReducer hook would be used with a state object, but let’s start with a little gelato counter to help understand the difference between the hook's conventions and the API. Our gelatoReducer takes 2 arguments: The current state, and an "action" that the dispatch function (that'd be setGelatoAmount) is called with. The useReducer hook for our little <Gelato /> component might look like over engineering, but it’s just for the sake of the example! 🍨 Twitter post and Raw code
Setting state with useReducer React With class components, instead of using the “setState” hook directly, you would use this.setState. This is because in class components, states are handled as objects. You can call it with any amount of properties, and those same properties would be the ones updated. In this example, we mimic the same way that same way of doing setState in class components and modify the reducer. Twitter post and Raw code
Constructors JavaScript Constructors in JS Twitter post and Raw code
Setters and Getters JavaScript JS class with a setter and getter Twitter post and Raw code
Template Literals JavaScript Template literals for string interpolation or multi-lined strings Twitter post and Raw code
getComputedStyle JavaScript getComputedStyle method to return an object containing an element's CSS properties. Twitter post and Raw code
Math.floor JavaScript Simple example of the Math.floor() method Twitter post and Raw code
Nullish coalescing operator JavaScript Using the Nullish coalescing operator ?? Twitter post and Raw code
Arrow functions JavaScript Arrow functions in JS => Twitter thread and Raw code
Logical OR assignment JavaScript Logical OR assignment in JS Twitter post and Raw code
Logical AND assignment JavaScript Logical AND assignment in JS &&= Twitter post and Raw code
Logical AND assignment JavaScript Logical AND assignment in JS &&= Twitter post and Raw code
Emptying an array JavaScript Empty an array in JS Twitter post and Raw code
Factorial (recursive) JavaScript Intro to recursion with a factorial function Twitter thread and Raw code
try...catch JavaScript The try...catch statement Twitter post and Raw code
Promise with setTimeout JavaScript Making your JavaScript wait for a specific amount of seconds. Twitter post and Raw code
Math object (min, max) JavaScript Using the Math.min() and Math.max() object Twitter post and Raw code
Set JavaScript Using Set in JS object Twitter thread and Raw code
Merging arrays JavaScript Merging arrays with the spread operator Twitter post and Raw code
Remove duplicates JavaScript How to remove duplicates inside your array. Twitter post and Raw code
Ternary JavaScript Using the ternary operator in JS. Twitter post and Raw code
Destructuring objects JavaScript Destructuring objects in JS Twitter thread and Raw code
Transgender flag 🏳️‍⚧️ CSS Styles for the transgender flag Twitter post and Raw code
Array destructuring JavaScript Destructuring with arrays Twitter post and Raw code
Object.entries JavaScript The Object.entries returns an array of arrays with a key and a value. Twitter post and Raw code
Reverse a string JavaScript How to reverse a string with comments to the code snippet on each individual step to help break it down. Twitter post and Raw code
Object.values JavaScript How the Object.values method returns an array of your object's properties. Twitter post and Raw code
Object.keys JavaScript Use Object.keys() to collect all the key names from any object. This can be useful once you obtain the array, because you're then able to loop through it! Twitter post and Raw code
Sorting arrays JavaScript Avoid sorting big amounts of data in the frontend. It can be an expensive operation, so it is preferable to be done in the backend. Twitter post and Raw code
transform-origin CSS It is used with the transform property to change the initial point of your transformation. Give it values such as: right, bottom, lengths, or percentages. The arguments start with the horizontal position, followed by the vertical position. Twitter post and Raw code
aspect-ratio CSS Use the aspect-ratio property to keep your boxes' dimensions proportional to each other using a ratio. It accepts a ratio as its argument in width/height form. Twitter post and Raw code
Falsy values JavaScript JavaScript tends to evaluate the type of values to Boolean when working with conditional statements such as if...else, or loops like do...while. Here are examples of possible falsy values. Twitter post and Raw code
Equality and strict equality operator JavaScript The biggest difference between the equality (==) and strict equality (===) is that the equality operator tries to compare and convert variables that have different types, whereas the strict equality operator does not try to convert types. Twitter post and Raw code
Converting a String to a Number JavaScript A brief example on how to convert Strings to Numbers using either JavaScript's Number constructor, or the parseInt function. This can be useful when trying to take a value from the user's input in a form, but you want it as a Number instead. Twitter post and Raw code
The typeof operator JavaScript Not having to assign types to variables in JS also means their types might change over time. An useful way of using it is when a variable might be undefined, and you want to catch it in that case. Twitter post and Raw code
clamp() CSS The clamp function will clamp your element's value between your given minimum value, maximum value, based on your ideal value. This function is useful when working with fluid typography, aka when you want your font-size to reflect the screen size. Twitter post and Raw code
min() and max() CSS Think of the min() as a function that returns the maximum value that your element's property can have, and vice-versa for the max() function. Twitter post and Raw code
Combining filter functions CSS Did you know that you can combine CSS filter functions together? The possibilities are endless. Twitter post and Raw code
while vs. do...while JavaScript Here's a brief example below about the do...while vs. while loop statements. Cases where you want to prompt a game once is great for a do...while statement, because the game will appear at least once, while the user doesn't quit. Twitter post and Raw code
innerText JavaScript Forgot to insert text in your HTML document? Have no fear, JavaScript HTMLElement.innerText is here! 🦸‍♀️ Prioritize using this property instead of the innerHTML property to avoid external cross-site scripting (XSS) attacks on your page. 🛡️ Twitter post and Raw code
grayscale() CSS This function will accept a length, or a percentage as its argument, giving you that dark, eerie, and beautiful feel to your now monochrome elements. Twitter post and Raw code
contrast() CSS Bring out the colors on your elements with the CSS contrast() function. I like to use it to make the colors on my images more intense, or tone it down by giving it a lower value. This function accepts a number, or a percentage as an argument. Twitter post and Raw code
blur() CSS Blur the lines on your elements with the CSS blur() function. This function will accept a length as its argument. Twitter post and Raw code
brightness() CSS Shed some light on your elements with the CSS brightness() function. It takes a number, or a percentage as an argument. That argument is then multiplied by the default value of 1 for your desired light intensity. 💡 Twitter post and Raw code
The lorem Emmet abbreviation HTML Don't know what to write? This Emmet abbreviation is pretty useful for summoning dummy text. Simply start typing "lorem", and add a number to specify the number of words you want in your paragraph. 📜 Twitter post and Raw code
The HTML template Emmet shortcut HTML I recently learned a new fun Emmet shortcut to quickly generate a HTML template using only the exclamation point (!) symbol ❗️ Twitter post and Raw code
The HTML markup Emmet shortcut HTML It is possible to use Emmet abbreviations to generate your markup quickly. They are similar to CSS selectors. In the related code snippet, you can see how to generate markup quickly and avoid repetition. Twitter post and Raw code
The Date constructor JavaScript Use the new Date() constructor to get back a Date object, like in the example below. 📅 Twitter post and Raw code
transform: skew CSS The skew() function is used to distort elements, taking degrees as its arguments for the its x-axis and y-axis. Elements with class .nachos will skew 10% of a turn on the x-axis, while .pierogi will skew 10 degrees on the x-axis and 20 degrees on the y-axis. Official post, sketch, and raw code
transform: rotate CSS Use the rotate() function to tilt around your elements. It accepts an angle in degrees as its argument. In the related code snippet, elements with the .bunny class will rotate 90 degrees to the right. Official post, sketch, and raw code
transform: translate CSS Use the translate() function to position your elements. It accepts x, y lengths as its values. In the related code snippet, the div tag will move 100% of its width to the right 👉. The p tag will move 10px to the right 👉, and 20px downwards 👇. Official post, and raw code
Spread syntax ... JavaScript Spreading ... can be useful in JS when you need to copy objects' properties or elements within an array. Use it to dynamically create your objects and arrays. Official post, and raw code
Rest parameters JavaScript You don't know how many arguments your function will need? Try the rest params syntax! If you recall the post on the spread syntax, you might notice they look similar. Funny thing is, they're actually opposites! The rest parameter syntax is a way to catch any remaining variables we didn't account for. It's useful to think of it as they are unlimited amounts of arguments to a function. The way to indicate that is with the ... notation. Official post, and raw code

Getting Started

Fork or clone the repository.


Local Commands

In this current section, you can find the command to run the code snippet in your machine:

$ node <filename>

Contributing

  1. Fork it
  2. Create your feature branch with specs (git checkout -b my-cute-feature).
  3. Commit your changes (git commit -m 'Added my cute feature').
  4. Push to the branch (git push origin my-cute-feature).
  5. Create your new pull request.

Contributors


Tommie Nguyễn


Gui Bibeau


Have a question or suggestion?

Contact me on Twitter, send an email to [email protected], or create a pull request on this project.


About

Code snippets to help grasp the concepts of the web.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published