Categories
React Hooks

Top React Hooks — Input Handling and Utilities

Spread the love

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

Then we can use it by writing:

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

export default function App() {
  const { active, bind } = useActive();

  const styles = {
    emphasis: {
      backgroundColor: active ? "yellow" : "red",
      color: active ? "black" : "white",
      padding: 5,
      width: 55,
      textAlign: "center"
    }
  };

  return (
    <div {...bind}>
      <span style={styles.emphasis}>{active ? "red" : "white"}</span>
      <p>{active.toString()}</p>
    </div>
  );
}

We spread the bind object to the outer div to let us watch whether the items inside are active or not.

Now when we click it, we get the styles in the emphasis property displayed.

The active state changes when we click in and out of the outer div.

It’s active when we click inside the outer div.

It also provides the useDidMount hook as a replacement of the componentDidMount method in React.

We can use it by writing:

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

export default function App() {
  useDidMount(() => {
    console.log("hello world");
  });

  return <div />;
}

We just put whatever we want to run in the useDidMount callback to run it.

The useFormField hook lets us handle form values with ease.

For instance, we can write:

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

export default function App() {
  const form = {
    name: useFormField(),
    age: useFormField()
  };

  const onSubmit = event => {
    event.preventDefault();
    if (!onValidate()) {
      return;
    }
    alert("Success");
    onReset();
  };

  const onReset = () => Object.values(form).map(({ reset }) => reset());

  const onValidate = () => {
    let isValid = true;
    Object.values(form).map(({ isEmpty, validate }) => {
      validate();
      if (isEmpty) {
        isValid = false;
      }
    });
    return isValid;
  };

  return (
    <div>
      <form onSubmit={onSubmit}>
        <div>
          <label htmlFor="name">Name</label>
          <input id="name" {...form.name.bind} placeholder="name" />
          {form.name.isValid && <p>Name is required*</p>}
        </div>
        <div>
          <label htmlFor="age">Age</label>
          <input id="age" {...form.age.bind} type="number" placeholder="age" />
          {form.age.isValid && <p>Age is required*</p>}
        </div>
        <div>
          <button type="submit">Submit</button>
          <button type="button" onClick={onReset}>
            Reset
          </button>
        </div>
      </form>
    </div>
  );
}

to create a form with the name and age fields.

We pass everything in the form.name.bind and form.age.bind properties into the input to let us handle the form values.

Then we can use the isValid property of each field to check or validity.

The onReset function gets all the form fields and call reset on them.

There’s also a validate method in each form field to validate them.

isEmpty check whether it’s empty or not.

These are all provided by the useFormField hook.

Conclusion

The Melting Pot library lets us do many things that we would otherwise have to write ourselves.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *