Categories
Useful APIs

Useful Free APIs — Arts Data

In the software development world, practice makes perfect. Therefore, we should find as many ways to practice programming as possible. With free public APIs, we can practice programming by creating apps that use those APIs.

In this article, we’ll look at some practice project ideas that can use some of those APIs.

Behance

The Behance API is an API with various design data that we can use.

We can access it with an API key.

We can use its endpoints to get projects, users, creative fields, and collections.

It comes with a JS wrapper, PHP library, a Ruby package, and a Python package.

Cooper Hewitt

The Cooper Hewitt API returns the data stored in the Smithsonian Design Museum.

To access it, we need to acquire an API token.

Once we created an API key, we can get various kinds of data like colors, departments, shop items, brands, videos, visitor data, and more.

Also, we can get gallery data like opening hours and whether the museum is open or not.

We can also get data for specific rooms.

Images are also available for retrieval.

Dribbble

The Dribbble API is another API that lets us designer data.

We need to authenticate with OAuth before we can access its data.

Data that we can get include projects, shots, users, and jobs.

The data can be read and manipulated with the endpoints.

Harvard Art Museums

The Harvard Art Museums API lets us access data provided by the museum.

To access the API, we need to create an API key.

We can access many kinds of data with this API.

We can access person, exhibitions,m publication, gallery, and activity data.

Also, we can get art created by a given technique.

Images, audio, and video are also available with this API.

We can explore the museum by getting data from this API with the Museum Explorer.

The Art Explorer lets us browse through collections with this API.

This API can be used from the browser directly and also from the server-side.

There are examples of how to access this API in the documentation.

Iconfinder

The Iconfinder API is a JSON API that lets us access resources on the service, like icons, icon sets, categories, styles, authors, etc.

An API key is required to access this API.

We can get icon set details, icon author data, icons by categories, icon styles, and more with this API.

Icon license information is also available for icons.

Icons8

The Icons8 API is another API that lets us access icon data.

This API has fewer endpoints than the Iconfinder API.

We can use it to search for data, metadata, and web fonts.

Authentication is done by OAuth.

HTTPS is available with this API.

Noun Project API

The Noun Project API lets us access icon data.

We can access them by their collection or access individual icon data.

Fields returned include URL, author, name, and more.

OAuth authentication is required to access this API.

Rijksmuseum

The Rijksmuseum API lets us access data from the Rijksmuseum.

We can access painting data from this API.

An API key is required to access the API.

We can access object metadata, bibliographic metadata, and user-generated content with this API.

Conclusion

There are many useful APIs to access arts data.

Categories
React

Framer Motion — Scrolling and Watching Motion Values

With the Framer Motion library, we can render animations in our React app easily.

In this article, we’ll take a look at how to get started with Framer Motion.

useElementScroll

The useElementScroll hook returns motion values that updated when the element scrolls.

For example, we can write:

import React, { useRef } from "react";
import { motion, useElementScroll } from "framer-motion";

export default function App() {
  const ref = useRef();
  const { scrollYProgress } = useElementScroll(ref);

  return (
    <div ref={ref} style={{ overflow: "scroll", height: 200 }}>
      <motion.div style={{ scaleY: scrollYProgress }}>
        {Array(100)
          .fill()
          .map((_, i) => (
            <p key={i}>{i}</p>
          ))}
      </motion.div>
    </div>
  );
}

We set the scaleY value to the scrollYProgress motion value.

Then the p elements that are lower are taller.

We just have the overflow property set to 'scroll' and a fixed height for this hook to calculate the scroll progress.

useViewportScroll

The useViewportScroll hook returns the motion values that update when the viewport scrolls.

For example, we can write:

import React, { useEffect } from "react";
import { motion, useViewportScroll } from "framer-motion";

export default function App() {
  const { scrollYProgress } = useViewportScroll();

  useEffect(() => {
    scrollYProgress.onChange((latest) => {
      console.log(latest);
    });
  }, []);

  return (
    <motion.div>
      {Array(100)
        .fill()
        .map((_, i) => (
          <p key={i}>{i}</p>
        ))}
    </motion.div>
  );
}

to get the scrollYProgress , which has the latest value of the vertical scroll progress.

Its value is between 0 and 1.

The value is set as the value of the latest parameter.

Other value this hook returns includes scrollX , which is the horizontal scroll distance in pixels.

The scrollY motion value has the vertical scroll distance in pixels.

And scrollXProgress has the horizontal scroll progress between 0 and 1.

onChange

We can watch for motion value changes with the onChange method.

For example, we can call it by writing:

import { motion, transform, useMotionValue } from "framer-motion";
import React, { useEffect } from "react";

export default function App() {
  const x = useMotionValue(0);
  const y = useMotionValue(0);
  const opacity = useMotionValue(1);

  useEffect(() => {
    function updateOpacity() {
      const maxXY = Math.max(x.get(), y.get());
      const newOpacity = transform(maxXY, [0, 100], [1, 0.1]);
      opacity.set(newOpacity);
    }

    const unsubscribeX = x.onChange(updateOpacity);
    const unsubscribeY = y.onChange(updateOpacity);

    return () => {
      unsubscribeX();
      unsubscribeY();
    };
  }, []);

  return (
    <motion.div
      drag
      style={{ x, opacity, backgroundColor: "red", width: 100, height: 100 }}
    />
  );
}

We call onChange in the useEffect callback.

We call x.onChange to watch the latest value of x .

And we call y.onChange to watch the latest value of y .

It returns a function to let us unsubscribe to the changes.

The updateOpacity function gets the latest value of x and y and then compute the opacity from it.

We call opacity.set to set the value of the opacity motion value.

Then we render the values by passing it into the style prop.

destroy

The destroy method destroys and clean up subscribers.

We call this on a motion value object.

Conclusion

We can watch for motion value changes to create animations with Framer Motion.

Also, we can watch for scrolling progress with it.

Categories
React

Framer Motion — Animation Hooks

With the Framer Motion library, we can render animations in our React app easily.

In this article, we’ll take a look at how to get started with Framer Motion.

useMotionTemplate

We can use the useMotionTemplate hook to combine multiple motion values into one using a template string literal.

For example, we can write:

import React from "react";
import {
  motion,
  useSpring,
  useMotionValue,
  useMotionTemplate
} from "framer-motion";

export default function App() {
  const shadowX = useSpring(10);
  const shadowY = useMotionValue(10);
  const shadow = useMotionTemplate`drop-shadow(${shadowX}px ${shadowY}px 20px rgba(0,0,0,0.3))`;

  return (
    <>
      <motion.div
        style={{
          filter: shadow,
          width: 100,
          height: 100,
          backgroundColor: "red"
        }}
      ></motion.div>
    </>
  );
}

to combine the shadowX and shadowY motion values by using the useMotionTenmplate tag.

We pass in the shadowX and shadowY values to create the drop shadow effect.

And we pass that into the style prop.

useTransform

The useTransform hook lets us create a motion value that transforms the output of another motion value with a function.

For example, we can write:

import React from "react";
import { motion, useMotionValue, useTransform } from "framer-motion";

export default function App() {
  const x = useMotionValue(10);
  const y = useTransform(x, (value) => value * 2);

  return (
    <motion.div
      style={{ x, y, width: 100, height: 100, backgroundColor: "red" }}
    />
  );
}

We create the x motion value with the useMotionValue hook.

Then we call the useTransform hook with the x motion value and a function to return a value for the y motion value.

Then we pass them both into the style prop to position the div.

We can use it to return a range of values.

To do this, we write:

import React from "react";
import { motion, useMotionValue, useTransform } from "framer-motion";

export default function App() {
  const x = useMotionValue(0);
  const xRange = [-200, -100, 100, 200];
  const opacityRange = [0, 1, 1, 0];
  const opacity = useTransform(x, xRange, opacityRange);

  return (
    <motion.div
      animate={{ x: 200 }}
      style={{ opacity, x, width: 100, height: 100, backgroundColor: "red" }}
    />
  );
}

We create the xRange array to use it to map to the values of opacityRange .

If x is -200, then opacity is 0. If x is -100, then opacity is 1, and so on.

We then use that to render the div with the position given by the x and y values.

The opacity is set to the value of the div.

useSpring

The useSpring hook lets us create a motion value that when it’s set, will use a spring animation to animate to its new state.

For example, we can write:

import React from "react";
import { motion, useSpring } from "framer-motion";

export default function App() {
  const x = useSpring(0, { stiffness: 300 });
  const y = useSpring(x, { damping: 10 });

  return (
    <motion.div
      animate={{ x: 200, y: 100 }}
      style={{ x, y, width: 100, height: 100, backgroundColor: "red" }}
    />
  );
}

We call useSpring to create the x motion value to create the spring effect.

stiffness is the stiffness coefficient. Higher stiffness decreases the number of oscillations.

damping is the ratio to reduce the magnitude of the oscillation.

We use the x and y values to animate the position of the div.

Conclusion

We can use various hooks provided by Framer Motion to animate our elements.

Categories
Modern JavaScript

Best of Modern JavaScript — Child Classes

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at how to define classes with JavaScript.

Computed Method Names

We can add methods with computed property names.

For example, we can write:

class Foo {
  ['foo' + 'Bar']() {}
}

We pass an expression that returns a string or symbol into the square brackets to create a method with the given identifier.

We can also pass in a symbol by writing:

class Foo {
  [Symbol.iterator]() {
    //...
  }
}

Generator Methods

We can add generator methods to a class.

For example, we can write:

class Iterable {
  constructor(arr) {
    this.arr = arr;
  } 

  *[Symbol.iterator]() {
    for (const a of this.arr) {
      yield a;
    }
  }
}

We create an Iterable class with the constructor and a method with the Symbol.iterator method.

This makes our Iterable instance iterable.

The method is a generator as indicated by the * symbol.

And we use yield to return and pause each item.

We can then use it with a for-of loop by writing:

class Iterable {
  constructor(arr) {
    this.arr = arr;
  }

  *[Symbol.iterator]() {
    for (const a of this.arr) {
      yield a;
    }
  }
}

for (const x of new Iterable(['foo', 'bar', 'baz'])) {
  console.log(x);
}

And we get each entry of the array we passed in logged.

Subclassing

We can create subclasses from base classes.

The extends keyword lets us create subclasses.

For example, we can write:

class Person {
  constructor(name) {
    this.name = name;
  }
  toString() {
    return `(${this.name})`;
  }
}

class Employee extends Person {
  constructor(name, title) {
    super(name);
    this.title = title;
  }
  toString() {
    return `(${super.toString()}, ${this.title})`;
  }
}

We created the Employee class with the extends keyword to create a subclass of Person .

In the constructor of Employee , we call super to call the Person constructor from there.

This is required before we access this in the subclass.

We set the this.title property with the title parameter’s value.

In the toString method, we call super.toString to call toString of the Person instance.

If we create an instance of Employee , we can check the class that it’s created from.

For instance, we can write:

const emp = new Employee('jane', 'waitress');
console.log(emp instanceof Person);
console.log(emp instanceof Employee);

They both return true and as we expect.

Person is the base class and Employee is the child class.

The Prototype of a Subclass is the Superclass

The class syntax is just a convenient way to create constructors, so it sticks to the prototypical inheritance model.

The prototype of a subclass is the superclass.

If we have:

class Person {
  constructor(name) {
    this.name = name;
  }
  toString() {
    return `(${this.name})`;
  }
}

class Employee extends Person {
  constructor(name, title) {
    super(name);
    this.title = title;
  }
  toString() {
    return `(${super.toString()}, ${this.title})`;
  }
}

Then:

console.log(Object.getPrototypeOf(Employee) === Person)

logs true .

Static properties are inherited from the base class by the child class.

For example, if we have:

class Foo {
  static baz() {
    return 'baz';
  }
}

class Bar extends Foo {}

Then we can call:

Bar.baz()

We can also call static methods in child classes:

class Foo {
  static baz() {
    return 'baz';
  }
}

class Bar extends Foo {
  static baz() {
    return `child ${super.baz()}`;
  }
}

Conclusion

We can add computed method names, static members, and get parent class members from child classes.

Categories
Modern JavaScript

Best of Modern JavaScript — Class Checks and Instantiation

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at how to define classes with JavaScript.

Class Details

There are many details in classes.

The value we extend can be an arbitrary expression.

For example, we can extend a class that’s resulted from calling a function:

class Foo extends combine(Foo, Bar) {}

Checks

The JavaScript interpreter makes some checks when we create our classes.

A class name can’t be eval or arguments .

Duplicate class names aren’t allowed.

The name constructor can be used for a normal method and not getters, setters, or generator methods.

Classes can’t be called as a function.

If we do, a TypeError will be thrown.

Prototype methods can’t be used as constructors.

So we can’t write something like:

class Foo {
  bar() {}
}
new Foo.prototype.bar();

If we run that, we’ll get the ‘Uncaught TypeError: Foo.prototype.bar is not a constructor’ error.

Property Descriptors

Static properties of a class Bar are writable and configurable but not innumerable.

Bar.prototype isn’t writable, enumerable, or configurable.

Bar.prototype.constructor isn’t writable or enumerable, but it’s configurable.

Properties of Bar.prototype are writable and configurable, but it’s not enumerable.

This means we can update many properties dynamically.

Classes have Inner Names

A class has its own name property to return to its inner name.

Its name can also be used in the class itself.

For example, we can write:

class Foo {
  bar() {
    console.log(Foo.baz);
  }
}
Foo.baz = 1;

We referenced Foo to get the static property.

This is true even if we assign the class to a variable.

For instance, if we have:

const Bar = class Foo {
  bar() {
    console.log(Foo.baz);
  }
}
Bar.baz = 1;new Bar().bar();

Then the bar method call still logs 1.

This means we can refer it with the original name internally.

Subclassing

We create subclasses by using the extends keyword.

For static methods, they’re inherited directly by the subclass.

For instance, if we have:

class Person {
  static logName() {
    console.log(Person.name)
  }
}

class Employee extends Person {}
console.log(Person.logName === Employee.logName)

Then the console log will log true .

The prototype of a JavaScript class is Function.prototype .

This means that the JavaScript class is actually a function.

We can see this by writing:

class Person {
  static logName() {
    console.log(Person.name)
  }
}

console.log(Object.getPrototypeOf.call(Object, Person) === Function.prototype)

We call the Object.getPrototypeOf method to get the prototype of the Person class.

Then we checked that against the Function.prototype .

And this logs true .

So we know classes are functions underneath the hood.

Initializing Instances

Class instances are initialized by writing:

function Person(name) {
  this.name = name;
}

in ES5.

In ES6, the base constructor is created with the super method.

This triggers a parent constructor call.

In ES5, the super constructor is called when we use new to call the constructor.

It’s invoked with the function call.

Conclusion

When we create classes, JavaScript interpreter does many checks.

Also, static methods are inherited by subclasses, and classes are functions.