Categories
React Hooks

Top React Hooks — Keypresses and Intersection

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

react-use

The react-use library is a big library with many handy hooks.

We can use the useIntersection hook to detect whether an element is obscured or fully in view.

To use it, we can write:

import React from "react";
import { useIntersection } from "react-use";

export default function App() {
  const intersectionRef = React.useRef(null);
  const intersection = useIntersection(intersectionRef, {
    root: null,
    rootMargin: "0px",
    threshold: 1
  });

  return (
    <>
      {Array(50)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
      <div ref={intersectionRef}>
        {intersection && intersection.intersectionRatio < 1
          ? "Obscured"
          : "Fully in view"}
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. In varius
          nisl quis nibh laoreet, vitae feugiat nisi maximus. Nullam vitae mi
          magna. Fusce lorem lacus,
        </p>
      </div>
    </>
  );
}

We created a ref that we pass into the useIntersection hook and the element that we want to watch.

The hook takes a few options.

root is the root element.

rootMargin is the margin of the root.

threshold is the threshold to determine whether the intersection exists.

The useKey hook lets us run a handler when a keyboard key is pressed.

For instance, we can write:

import React from "react";
import { useKey } from "react-use";

export default function App() {
  const [count, set] = React.useState(0);
  const increment = () => set(count => count + 1);
  useKey("ArrowDown", increment);

  return <div>Press arrow down: {count}</div>;
}

We use the useKey hook with the string with the key name and the function to run when the key is pressed.

It’s also available as a render prop.

To use it, we write:

import React from "react";
import UseKey from "react-use/lib/comps/UseKey";

export default function App() {
  const [count, set] = React.useState(0);
  const increment = () => set(count => count + 1);

  return (
    <>
      <UseKey filter="ArrowDown" fn={increment} />
      <div>Press arrow down: {count}</div>
    </>
  );
}

We used the UseKey component with the filter and fn props.

filter has the key name.

fn has the function to run when the key is pressed.

We can also use the useKey hook with a predicate:

import React from "react";
import { useKey } from "react-use";

export default function App() {
  const [count, set] = React.useState(0);
  const increment = () => set(count => count + 1);

  const predicate = event => event.key === "ArrowDown";
  useKey(predicate, increment, { event: "keyup" });

  return (
    <>
      <div>Press arrow down: {count}</div>
    </>
  );
}

We have the predicate function to check the key property with the string of the key name.

We pass that into the useKey hook with the object with the event name.

The useKeyPress hook lets us listen for key presses.

For instance, we can write:

import React from "react";
import { useKeyPress } from "react-use";
const keys = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];

export default function App() {
  const states = [];
  for (const key of keys) states.push(useKeyPress(key)[0]);

  return (
    <div>
      Try pressing numbers
      <br />
      {states.join(", ")}
    </div>
  );
}

We have the useKeyPress hook with the argument being the key name.

This will let us detect whether the given key is pressed.

It returns an array with the first entry being true if the key is pressed.

Conclusion

The react-use package has hooks to detect key presses and detect intersections.

Categories
React Hooks

Top React Hooks — Keyboard and Query Strings

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

react-use

The react-use library is a big library with many handy hooks.

The useKeyboardJs hook lets us detect key combo presses.

For instance, we can write:

import React from "react";
import useKeyboardJs from "react-use/lib/useKeyboardJs";

export default function App() {
  const [isPressed] = useKeyboardJs("a + b");

  return <div>[a + b] pressed: {isPressed ? "Yes" : "No"}</div>;
}

We also need to install the keyboardjs package for this hook to work.

To use the hook, we just pass in the string.

And it returns an array with the first entry being the key combo that’s pressed.

Then when we press both keys a and b, we’ll show ‘Yes’.

The useKeyPressEvent hook fires both keydown and keyup callbacks.

But it only triggers each callback once per press cycle.

It’ll fire the keydown callback only once if we press and hold a key.

For instance, we can use it by writing:

import React from "react";
import { useKeyPressEvent } from "react-use";

export default function App() {
  const [count, setCount] = React.useState(0);

  const increment = () => setCount(count => count + 1);
  const decrement = () => setCount(count => count - 1);
  const reset = () => setCount(count => 0);

  useKeyPressEvent("[", increment, increment);
  useKeyPressEvent("]", decrement, decrement);
  useKeyPressEvent("r", reset);

  return (
    <div>
      <p>Count: {count}</p>
    </div>
  );
}

We create the functions increment , decrement , and reset to change the count state.

The useKeyPressEvent hook lets us listen to key presses.

The first argument is the key.

The 2nd and 3rd arguments are the callbacks that run when the key is down and up.

The useLocation hook lets us track the browser’s location.

We need to install the Geolocation API polyfill for IE to support IE.

To use it, we write:

import React from "react";
import { useLocation } from "react-use";

export default function App() {
  const state = useLocation();

  return <pre>{JSON.stringify(state, null, 2)}</pre>;
}

We have various properties like in the state like trigger , state m hash , host , hostname , etc.

hash hash the URL segment after the pound sign.

hostname has the hostname.

href has the whole URL.

origin has the root URL segment.

port has the port.

pathname has the pathname without the root part.

protocol has the protocol that we communicate through.

search has the query string.

The useSearchParam hook lets us track location search params.

For instance, we can use it by writing:

import React from "react";
import { useSearchParam } from "react-use";

export default function App() {
  const foo = useSearchParam("foo");

  return (
    <>
      <div>
        <button
          onClick={() =>
            history.pushState({}, "", `${location.pathname}?foo=123`)
          }
        >
          123
        </button>
        <button
          onClick={() =>
            history.pushState({}, "", `${location.pathname}?foo=456`)
          }
        >
          456
        </button>
        <button
          onClick={() =>
            history.pushState({}, "", `${location.pathname}?foo=789`)
          }
        >
          789
        </button>
        <p>{foo}</p>
      </div>
    </>
  );
}

In each button, we called pushState to go to a URL with different query strings.

The useSearchParam hook takes the key of the query string to get the value of and returns the value.

Then we’ll see the return value rendered.

Conclusion

The react-use package has hooks to detect key presses and query strings.

Categories
React Hooks

Top React Hooks — Idleness, Geolocation, and Hashes

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

react-use

The react-use library is a big library with many handy hooks.

The useGeolocation hook lets us get the location data within our React app.

We can use it by writing:

import React from "react";
import { useGeolocation } from "react-use";

export default function App() {
  const state = useGeolocation();

  return <>{JSON.stringify(state)}</>;
}

We use the useGeolocation to get various pieces of data.

It includes the accuracy, latitude, longitude, altitude, speed, and loading state.

The useHover and useHoverDirty gooks lets us watch for hovering of an element.

To use the useHover hook, we can write:

import React from "react";
import { useHover } from "react-use";

export default function App() {
  const element = hovered => <div>Hover me {hovered.toString()}</div>;
  const [hoverable, hovered] = useHover(element);

  return (
    <div>
      {hoverable}
      <div>{hovered.toString()}</div>
    </div>
  );
}

We use the useHover hook with the element of our choice.

The element is a function that takes the hovered parameter and returns some elements.

useHover returns an array with the hoverable and hovered variables.

hoverable indicates whether an element is hoverable.

hovered indicates whether the element is hovered on.

useHover uses onMouseEnter and onMouseLeave to watch for hovering.

useHoverDirty accept a React ref.

And it sets its handlers to the onmouseover and onmouseout properties.

To use it, we write:

import React from "react";
import { useHoverDirty } from "react-use";

export default function App() {
  const ref = React.useRef();
  const isHovering = useHoverDirty(ref);

  return (
    <div ref={ref}>
      <div>{isHovering.toString()}</div>
    </div>
  );
}

useHoverDirty takes a ref, which we also pass to the element we want to watch hover on.

It returns the isHovering variable which indicates whether we’re hovering on it or not.

useHash is a hook that tracks the browser location’s hash.

To use it, we can write:

import React from "react";
import { useHash, useMount } from "react-use";

export default function App() {
  const [hash, setHash] = useHash();

  useMount(() => {
    setHash("#/foo/page?userId=123");
  });

  return (
    <div>
      <div>
        <pre>{window.location.href}</pre>
      </div>
      <div>Edit hash: </div>
      <div>
        <input
          style={{ width: "100%" }}
          value={hash}
          onChange={e => setHash(e.target.value)}
        />
      </div>
    </div>
  );
}

to use it.

We use the useMount hook which changes the hash when the component mounts.

We did that with the setHash function returned by the useHash hook.

hash has the hash value with the pound sign.

When we get the window.location.href , we’ll get the whole URL with the hash.

The useIdle hook let us determine if the page id idle.

To use it, we write:

import React from "react";
import { useIdle } from "react-use";

export default function App() {
  const isIdle = useIdle(1000);

  return (
    <div>
      <div>User is idle: {isIdle ? "yes" : "no"}</div>
    </div>
  );
}

We use the useIdle hook with the time to idle in milliseconds in the argument.

It returns the isIdle boolean variable to indicate whether the page is idle or not.

Conclusion

The react-use package comes with many useful hooks like geolocation, watching hovering, and watching for idleness.

Categories
React Hooks

Top React Hooks —File Drop, Audio and Clicks

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

react-use

The react-use library is a big library with many handy hooks.

The useAudio hook creates an audio element.

It tracks the state and exposes playback controls.

For instance, we can write:

import React from "react";
import { useAudio } from "react-use";

export default function App() {
  const [audio, state, controls, ref] = useAudio({
    src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",
    autoPlay: true
  });

  return (
    <>
      {audio}
      <pre>{JSON.stringify(state, null, 2)}</pre>
      <button onClick={controls.pause}>Pause</button>
      <button onClick={controls.play}>Play</button>
      <button onClick={controls.mute}>Mute</button>
      <button onClick={controls.unmute}>Un-mute</button>
      <button onClick={() => controls.volume(0.1)}>Volume: 10%</button>
      <button onClick={() => controls.volume(0.5)}>Volume: 50%</button>
      <button onClick={() => controls.volume(1)}>Volume: 100%</button>
      <button onClick={() => controls.seek(state.time - 5)}>-5 sec</button>
      <button onClick={() => controls.seek(state.time + 5)}>+5 sec</button>
    </>
  );
}

to use the useAudio hook.

The argument is the object with the audio URL and autoPlay option.

controls has the methods to control the audio playback.

state has the audio playing state.

The state includes the time, duration, paused, muted, and volume.

The useClickAway hook lets us trigger a callback when the user clicks outside the target element.

For example, we can write:

import React from "react";
import { useClickAway } from "react-use";

export default function App() {
  const ref = React.useRef(null);
  useClickAway(ref, () => {
    console.log("clicked outside");
  });

  return (
    <div
      ref={ref}
      style={{
        width: 200,
        height: 200,
        background: "green"
      }}
    />
  );
}

to use the hook.

useClickAway takes a ref for the element to watch ad a callback that runs some code when we click outside that element.

We also pass in the ref to the element we want to watch the clicks outside so that we can watch for clicks outside.

The useCss hook lets us change CSS dynamically in our app.

To use it, we can write:

import React from "react";
import { useCss } from "react-use";

export default function App() {
  const className = useCss({
    color: "green",
    border: "1px solid green",
    "&:hover": {
      color: "blue"
    }
  });

  return <div className={className}>Hover me</div>;
}

Then useCss hook takes an object with some styles in it.

It returns the className which we can use to style our component.

We can use the useDrop hook to get the file that’s dropped into the container.

For instance, we can write:

import React from "react";
import { useDrop } from "react-use";

export default function App() {
  const state = useDrop({
    onFiles: files => console.log("files", files),
    onUri: uri => console.log("uri", uri),
    onText: text => console.log("text", text)
  });

  return (
    <div style={{ width: 200, height: 200, background: "orange" }}>
      Drop file here
    </div>
  );
}

The useDrop hook takes an object with some properties.

onFiles has the files object as the parameter and we can do things with it.

files has the files that have been dropped into the element.

onUri runs when we drop a URL and onText runs when we drop some text in there.

Conclusion

The react-use package has hooks to let us create audio elements, listen to clicks outside, and listen to file drops.

Categories
React Hooks

Top React Hooks — Drop Area, Speech, Full Screen, and Slider

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

react-use

The react-use library is a big library with many handy hooks.

useDropArea

The useDropArea hook lets us listen to file drops with elements.

For example, we can write:

import React from "react";
import { useDropArea } from "react-use";

export default function App() {
  const [bond, state] = useDropArea({
    onFiles: files => console.log("files", files),
    onUri: uri => console.log("uri", uri),
    onText: text => console.log("text", text)
  });

  return (
    <div {...bond} style={{ width: 200, height: 200, background: "orange" }}>
      Drop file here
    </div>
  );
}

We have the useDropArea hook that returns an object that we can use as props to make an element accept files being dropped into it.

The callbacks in the object are run when those items are dropped into it.

useFullscreen

To let us toggle full-screen mode, the useFullscreen hook lets us add full screen toggling capability to our app.

For instance, we can write:

import React from "react";
import { useFullscreen, useToggle } from "react-use";

export default function App() {
  const ref = React.useRef(null);
  const [show, toggle] = useToggle(false);
  const isFullscreen = useFullscreen(ref, show, {
    onClose: () => toggle(false)
  });

  return (
    <div ref={ref} style={{ backgroundColor: "white" }}>
      <div>{isFullscreen ? "Fullscreen" : "Not fullscreen"}</div>
      <button onClick={() => toggle()}>Toggle</button>
    </div>
  );
}

We have the useToggle hook to let us toggle full screen.

The useFullscreen hook takes a ref that we want to toggle fullscreen.

show is the state of the full-screen toggle.

toggle is a function to toggle show .

isFullScreen has the full-screen state.

useSlider

The useSlider state lets us add slider behavior to any HTML element.

It supports both mouse and touch events.

For example, we can write:

import React from "react";
import { useSlider } from "react-use";

export default function App() {
  const ref = React.useRef(null);
  const { isSliding, value, pos, length } = useSlider(ref);

  return (
    <div>
      <div ref={ref} style={{ position: "relative" }}>
        <p style={{ textAlign: "center", color: isSliding ? "red" : "green" }}>
          {Math.round(value * 100)}%
        </p>
        <div style={{ position: "absolute", left: pos }}>slide here</div>
      </div>
    </div>
  );
}

We use the useSlider hook with a ref to let us create a slide.

We pass the ref into the ref prop.

It returns an object with a few properties.

isSliding is a boolean that’s true if we’re sliding the slider.

value has the value of the slider.

pos has the position.

length has the length of the slide relative to the left.

useSpeech

useSpeech lets our app speak any text we pass into it.

For instance, we can use it by writing:

import React from "react";
import { useSpeech } from "react-use";

const voices = window.speechSynthesis.getVoices();

export default function App() {
  const state = useSpeech("a quick brow box jump over the dog", {
    rate: 0.8,
    pitch: 0.5,
    voice: voices[0]
  });

  return <pre>{JSON.stringify(state, null, 2)}</pre>;
}

To use it, we just pass in the text we want to speak as the first argument.

The 2nd argument has the voice settings.

It includes the speed, which is the rate , the pitch, and the voice to speak the text with.

It returns the state which tells us whether the text is being spoken, the rate, the pitch, and the language.

Conclusion

react-use lets us create a slider, a file drop area, toggle full screen, and speak text.