Categories
React Hooks

Top React Hooks — Hover, Toggles, and Titles

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.

Melting Pot

Melting Pot has a bunch of hooks that we can use in our React app.

It’s a utility library with many hooks.

To install it, we run:

npm install @withvoid/melting-pot --save

or:

yarn add @withvoid/melting-pot

We can then use the useHover hook to watch for the hovering on an element.

To use it, we write:

import React from "react";
import { useHover } from "@withvoid/melting-pot";

export default function App() {
  const { hover, bind } = useHover();
  const styles = {
    emphasis: {
      display: "inline-block",
      backgroundColor: "red",
      color: "white",
      padding: 5,
      width: 55,
      textAlign: "center"
    }
  };

  return (
    <div {...bind}>
      <p>Hover me</p>
      <p>
        Status: <span style={styles.emphasis}>{String(hover)}</span>
      </p>
    </div>
  );
}

We pass the bind object to the div so we can watch everything inside the div when they’re hovered.

Then we can get the hover state with the hover value returned by useHover .

The useKeyPress hook lets us watch for specific key presses.

To use it, we can write:

import React from "react";
import { useKeyPress } from "@withvoid/melting-pot";

export default function App() {
  const [isKeyPressed, key] = useKeyPress("a");

  return (
    <p>
      {isKeyPressed && "a is pressed"} {key}
    </p>
  );
}

We use the useKeyPress hook to get the keypress.

The argument is the key that’s pressed.

Then we can get the pressed state with the isKeyPress state.

key has the key that’s being watched.

The useOnlineStatus hook lets us get the online status of our app.

To use it, we write:

import React from "react";
import { useOnlineStatus } from "@withvoid/melting-pot";

export default function App() {
  const { online } = useOnlineStatus();
  return (
    <div>
      <p>{online ? "You Are Online" : "You Are Offline"}</p>
    </div>
  );
}

Then we can use the useOnlineStatus hook to get the online property that has the status.

The useTitle hook lets us set the title of our page.

For example, we can use it by writing:

import React from "react";
import { useTitle } from "@withvoid/melting-pot";

export default function App() {
  const [count, setCount] = React.useState(1);
  useTitle(count);
  const onChange = value => {
    setCount(count => count + value);
  };
  const onIncrement = () => onChange(1);
  const onDecrement = () => onChange(-1);

  return (
    <div>
      <section>
        <button type="button" onClick={onIncrement}>
          +
        </button>
        <p>Count {count}</p>
        <button type="button" onClick={onDecrement}>
          -
        </button>
      </section>
    </div>
  );
}

We get use the useTitle hook to set the title by the count.

The count is updated when we click the buttons.

So the latest value of it would be used to set the title.

The useToggle hook lets us watch for the toggling of a value.

For example, we can write:

import React from "react";
import { useToggle } from "@withvoid/melting-pot";

export default function App() {
  const { on, onToggle } = useToggle();

  return (
    <div>
      <button onClick={onToggle}>{on ? "On" : "Off"}</button>
    </div>
  );
}

to add the useToggle hook.

It returns an object with the on state that has the toggle state.

And the onToggle function lets us toggle the on state.

Conclusion

We can use the Melting Pot library to do many things including watching network state, setting titles, watching for hovering, and toggling states.

Categories
React Hooks

Top React Hooks — Github and States

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.

@d2k/react-github

@d2k/react-github is a series of React hooks that let us get data from Github.

To install it, we run:

npm i @d2k/react-github --save

Then we can use the useLatestRelease hook by writing:

import React from "react";
import { useLatestRelease } from "@d2k/react-github";

export default function App() {
  const { release, loading, error } = useLatestRelease("facebook", "react");

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

We get the latest errors by using the useLatestRelease hook with the user and repo name.

Then release has an object with the release data.

loading and error have the loading and error states.

We can use the useTaggedRelease hook to get a tagged release from our app.

To use it, we write:

import React from "react";
import { useTaggedRelease } from "@d2k/react-github";

export default function App() {
  const { release, loading, error } = useTaggedRelease(
    "facebook",
    "react",
    "v16.8.4"
  );
  return (
    <>
      <div>{JSON.stringify(release)}</div>
    </>
  );
}

It also has the useForks hook to get the forks of a repo.

The first argument is the user.

The 2nd argument is the repo.

The 3rd is the tag version.

For instance, we can write:

import React from "react";
import { useForks } from "@d2k/react-github";

export default function App() {
  const { forks, loading, error } = useForks("facebook", "react");

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

to get the forks of React.

@d2k/react-localstorage

@d2k/react-localstorage is a package with hooks to manipulating local storage.

To use it, we run:

npm i @d2k/react-localstorage --save

to install it.

Then we can use it by writing:

import React from "react";
import useLocalStorage from "@d2k/react-localstorage";

export default function App() {
  const [firstName, setFirstName, removeFirstName] =   useLocalStorage(
    "firstName",
    "mary"
  );
  const [lastName, setLastName, removeLastName] = useLocalStorage(
    "lastName",
    "smith"
  );

  return (
    <>
      <div>
        {firstName && lastName && (
          <p>
            Hello {firstName} {lastName}
          </p>
        )}
      </div>
    </>
  );
}

We used the useLocalStorage hook which returns the current value, a function to update the item with the given key, and remove the item with the given key in this order.

The key is the first argument of the hook.

The default value is the 2nd argument.

Then we can use them to update our local storage instead of manipulating it directly.

Hookstate

The Hookstate package lets us manage state globally in our app.

It can be used as an alternative to state management solutions like Redux or Mobx.

To install it, we run:

npm install --save @hookstate/core

or:

yarn add @hookstate/core

to install it.

Then we can use the hooks it comes with by writing:

import React from "react";
import { createState, useState } from "@hookstate/core";
const globalState = createState(0);

export default function App() {
  const state = useState(globalState);
  return (
    <>
      <p>Counter value: {state.get()}</p>
      <button onClick={() => state.set(p => p + 1)}>Increment</button>
    </>
  );
}

We use the createState function to create a global state.

Then we can pass that into the Hookstate’s useState hook so we can do stuff to it.

We call get to get the current state.

And we call set to set the new state.

Conclusion

There’re useful hooks for getting data from Github and managing local storage and app state.

Categories
React Hooks

Top React Hooks — Fetch, Scroll, and Modals

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.

fetch-suspense

We can use the fetch-suspense package to do fetch and display a loading component while the data is loading.

To use it, we can install it by running:

npm install fetch-suspense

or:

yarn add fetch-suspense

Then we can use it by writing:

index.js

import React, { Suspense } from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <Suspense fallback={<p>Loading...</p>}>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </Suspense>,
  rootElement
);

App.js

import useFetch from "fetch-suspense";
import React from "react";

export default function App() {
  const response = useFetch("https://api.agify.io/?name=michael", {
    method: "GET"
  });

  return <div className="App">{JSON.stringify(response)}</div>;
}

We add the Suspense component to the root component with the fallback component in the fallback prop.

Then in App , we use the useFetch hook to fetch the data we want.

The response is returned in the function.

Modali

The Modali package is a library for creating a modal.

We install it by running:

npm install --save modali

Then we can use it by writing:

import React from "react";
import Modali, { useModali } from "modali";

export default function App() {
  const [exampleModal, toggleExampleModal] = useModali();

  return (
    <div className="app">
      <button onClick={toggleExampleModal}>Click me</button>
      <Modali.Modal {...exampleModal}>Hello world</Modali.Modal>
    </div>
  );
}

We use the useModali hook to return the props for the Modali.Modal component.

The toggleExampleModal function is used to toggle the opening of the modal.

moment-hooks

The moment-hooks library is a library that comes with various utility hooks that we can use.

We can install it with:

yarn install moment-hooks

Then we can use it by writing:

import React from "react";
import { useOutsideClick } from "moment-hooks";

export default function App() {
  const ref = React.useRef();
  useOutsideClick(ref, () => console.log(" clicked outside"));
  return (
    <div className="app" ref={ref}>
      hello
    </div>
  );
}

We use the useOutsideClick hook by passing in the ref of the component that we want to check whether we clicked outside.

It also comes with the useArray hook to make handling state arrays easier.

We can use it to create a state array.

And we can use it to update the array with the functions returned by the hook.

For instance, we can write:

import React from "react";
import { useArray } from "moment-hooks";

export default function App() {
  const [list, actions] = useArray(["new item"]);

  return (
    <div className="app">
      <button onClick={() => actions.push("new item")}>add</button>
      {list.map(l => (
        <p>{l}</p>
      ))}
    </div>
  );
}

We have the actions object, which has array methods like push to add a new item to the array.

list has the array itself.

actions also has the removeIndex function to let us remove an item by its index.

The useLockBodyScroll hook disables scrolling on the body.

For instance, we can use it by writing:

import React from "react";
import { useLockBodyScroll } from "moment-hooks";

export default function App() {
  useLockBodyScroll(true);
  return (
    <div className="app">
      {Array(1000)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </div>
  );
}

We called the useLockBodyScroll hook with argument true to disable scrolling on the body.

Now we can’t scroll even if a list of items displayed that overflow the body.

Conclusion

fetch-suspense lets us the Suspense component while fetching data.

Modali is a hook for creating modals.

moment-hooks has many hooks that help us with various things

Categories
React Hooks

Top React Hooks — Browser APIs

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.

@21kb/react-device-orientation-hook

The @21kb/react-device-orientation-hook lets us get the orientation and angle of the screen.

To use it, we install it by running:

npm install --save @21kb/react-device-orientation-hook

or:

yarn add @21kb/react-device-orientation-hook

Then we can use it by writing:

import React from "react";
import useOrientation from "@21kb/react-device-orientation-hook";

export default function App() {
  const state = useOrientation({
    angle: 0,
    type: "landscape-primary"
  });
  const { angle, type } = state;

  return (
    <div className="App">
      {angle} {type}
    </div>
  );
}

We set the default angle and orientation with the type property.

Then we can get that returned with the useOrientation hook.

@21kb/react-notification-hook

We can use the notification hook to show native notifications with our browser.

To install it, we run:

npm install --save @21kb/react-notification-hook

or:

yarn add @21kb/react-notification-hook

Then we can use it by writing:

import React from "react";
import useNotification from "@21kb/react-notification-hook";

export default function App() {
  const notify = useNotification({
    title: "hello world",
    options: {
      dir: "rtl"
    }
  });

  return <button onClick={notify()}>Notify me!</button>;
}

The useNotificatiin hook returns a function to let us display a notification.

The title has the title of the notification.

options include the dir for the direction.

@21kb/react-online-status-hook

The @21kb/react-online-status-hook package lets us get the online status of our app.

We can use the useOnlineStatus or useOfflineStatus hook to get the online status.

We install it with:

npm install --save @21kb/react-online-status-hook

Then we can use it by writing:

import React from "react";
import { useOnlineStatus } from "[@21kb/react-online-status-hook](http://twitter.com/21kb/react-online-status-hook "Twitter profile for @21kb/react-online-status-hook")";
export default function App() {
  const status = useOnlineStatus();

  return <div>You are currently {status ? "online" : "offline"}.</div>;
}

useOfflineStatus does the same thing.

For example, we can write:

import React from "react";
import { useOfflineStatus } from "@21kb/react-online-status-hook";
export default function App() {
  const status = useOfflineStatus();

  return <div>You are currently {status ? "online" : "offline"}.</div>;
}

@21kb/react-page-visible-hook

The @21kb/react-page-visible-hook package provides us with a hook for getting the page visibility status of our app.

To install it, we run:

npm install --save @21kb/react-page-visible-hook

or:

yarn add @21kb/react-page-visible-hook

to install it.

Then we can use it by writing:

import React from "react";
import useVisible from "@21kb/react-page-visible-hook";

export default function App() {
  const state = useVisible();
  const { visibilityState } = state;

  return <>{visibilityState}</>;
}

The useVisible hook returns the visibility state of our app.

The value can be 'visible' or 'prerender' .

@21kb/react-dom-status-hook

The @21kb/react-dom-status-hook package provides us with a hook to get the ready state of our app.

We can install it by running:

npm install --save @21kb/react-dom-status-hook

or:

yarn add @21kb/react-dom-status-hook

Then we can use the useDomStatus hook by writing:

import React from "react";
import useDomStatus from "@21kb/react-dom-status-hook";

export default function App() {
  const { readyState } = useDomStatus();

  return <div>{readyState}</div>;
}

It returns an object with the readyState property to get the DOM loading state.

Conclusion

We can use various hooks to use various browser APIs.

Categories
Material UI

Material UI — Slider

Material UI is a Material Design library made for React.

It’s a set of React components that have Material Design styles.

In this article, we’ll look at how to add sliders with Material UI.

Discrete Sliders

We can add sliders to snaps to discrete values.

To do that, we set the marks prop to true .

For instance, we can write:

import React from "react";
import Slider from "@material-ui/core/Slider";

export default function App() {
  return (
    <form>
      <Slider marks />
    </form>
  );
}

to make an uncontrolled slider that snaps to the nearest 10.

Small Steps

We can change the steps with the steps prop.

For example, we can write:

import React from "react";
import Slider from "@material-ui/core/Slider";

export default function App() {
  return (
    <form>
      <Slider step={0.00001} marks />
    </form>
  );
}

to change the increment between each discrete value.

Custom Marks

We can add our own custom marks with the marks prop.

For example, we can write:

import React from "react";
import Slider from "@material-ui/core/Slider";

const marks = [
  {
    value: 0,
    label: "0m"
  },
  {
    value: 25,
    label: "25m"
  },
  {
    value: 50,
    label: "50m"
  },
  {
    value: 75,
    label: "75m"
  },
  {
    value: 100,
    label: "100m"
  }
];

export default function App() {
  return (
    <form>
      <Slider step={10} marks={marks} valueLabelDisplay="auto" />
    </form>
  );
}

We add the marks array with the value and label properties in each entry to show the labels with the text in the label property.

Restricted Values

We can restrict values to the ones that are in the marks array by setting step to null .

For example, we can write:

import React from "react";
import Slider from "@material-ui/core/Slider";

const marks = [
  {
    value: 0,
    label: "0m"
  },
  {
    value: 25,
    label: "25m"
  },
  {
    value: 50,
    label: "50m"
  },
  {
    value: 75,
    label: "75m"
  },
  {
    value: 100,
    label: "100m"
  }
];

export default function App() {
  return (
    <form>
      <Slider step={null} marks={marks} valueLabelDisplay="auto" />
    </form>
  );
}

Now we can only select the values that are marked in the marks array because of the null value we passed into the step prop.

Make Label Always Visible

We can make the labels always visible by setting the valueLabelDisplay prop to on .

For example, we can write:

import React from "react";
import Slider from "@material-ui/core/Slider";

const marks = [
  {
    value: 0,
    label: "0m"
  },
  {
    value: 25,
    label: "25m"
  },
  {
    value: 50,
    label: "50m"
  },
  {
    value: 75,
    label: "75m"
  },
  {
    value: 100,
    label: "100m"
  }
];

export default function App() {
  return (
    <form>
      <Slider step={10} valueLabelDisplay="on" marks={marks} />
    </form>
  );
}

Now we see the value above the slider dot.

Range Slider

We can allow users to select a value range with the Slider .

To do that, we can set an array as the value as the initial value.

For example, we can write:

import React from "react";
import Slider from "@material-ui/core/Slider";

export default function App() {
  const [value, setValue] = React.useState([20, 30]);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };
  return (
    <form>
      <Slider valueLabelDisplay="auto" value={value} onChange={handleChange} />
    </form>
  );
}

to make a range slider.

We set an array as the initial value of the value state to make the slider a range slider.

Vertical Sliders

We can make a slider vertical with the orientation prop set to vertical .

For instance, we can write:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Slider from "@material-ui/core/Slider";

const useStyles = makeStyles({
  root: {
    height: 300
  }
});

export default function App() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <Slider
        orientation="vertical"
        valueLabelDisplay="auto"
        defaultValue={30}
      />
    </div>
  );
}

to create a vertical slider.

We’ve to set the height of the wrapper so that the slider is displayed.

Track

We can set track to false to remove the track that’s displayed when we select a value.

To do that, we write:

import React from "react";
import Slider from "@material-ui/core/Slider";

export default function App() {
  return (
    <div>
      <Slider track={false} defaultValue={30} />
    </div>
  );
}

to remove th track.

We can also set it to inverted to change the track to be opposite of the default.

Non-Linear Scale

The scale is linear by default, but we can change it to a nonlinear scale with the scale prop set to a function.

We can write:

import React from "react";
import Slider from "@material-ui/core/Slider";

export default function App() {
  return (
    <div>
      <Slider scale={x => x ** 5} defaultValue={30} />
    </div>
  );
}

to change the scale.

Conclusion

We can add sliders to let users select a number or a range of numbers from a slider.