Categories
React Hooks

Top React Hooks — Forms and Forward Refs

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.

react-use

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

useMethods

The useMethods hook is a simpler useReducer hook implementation.

It lets us cache states so it’s useful for using complex computations.

For instance, we can write:

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

const initialState = {
  count: 0
};

function countMethods(state) {
  return {
    reset() {
      return initialState;
    },
    increment() {
      return { ...state, count: state.count + 1 };
    },
    decrement() {
      return { ...state, count: state.count - 1 };
    }
  };
}

export default function App() {
  const [state, methods] = useMethods(countMethods, initialState);

  return (
    <>
      <p>{state.count}</p>
      <button onClick={methods.increment}>increment</button>
      <button onClick={methods.decrement}>decrement</button>
      <button onClick={methods.reset}>reset</button>
    </>
  );
}

We created the countMethods function with the methods we can use to manipulate our state .

It returns the state as we want to by returning an object with various methods.

reset returns the initial state.

increment returns a state with count increased by 1.

decrement returns a state with count decreased by 1.

We passed the countMethods function into the useMethods hook along with the initialState .

Then that returns the state and the methods object that has the methods returned by countMethods .

We then called them when we click the buttons.

useEnsuredForwardedRef

The useEnsuredForwardedRef hook letrs us forward refs to a child component.

For instance, we can write:

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

const Foo = React.forwardRef((props, ref) => {
  const ensuredForwardRef = useEnsuredForwardedRef(ref);

  React.useEffect(() => {
    console.log(ensuredForwardRef.current);
  }, []);

  return <div ref={ensuredForwardRef} />;
});

export default function App() {
  return (
    <>
      <Foo />
    </>
  );
}

to use the hook.

We just pass in a ref to the useEnsuredForwardRef hook and it’ll return ensuredForwardRef .

It’ll never be undefined , so we can use it as we do in the useEffect callback.

useFormless

React-useFormless is a simple library that lets us create forms with a simple hook.

We can install it by running:

yarn add react-useformless

or

npm install react-useformless

Then we can use it by writing:

import React from "react";
import useFormless from "react-useformless";

const options = {
  initialValues: {
    name: "",
    password: ""
  },
  validate: (name, value) => {
    const validators = {
      name: name => (name.length > 0 ? "" : "name is requred"),
      password: password => (password.length > 0 ? "" : "password is required")
    };

const errorFn = validators[name];
    return errorFn(value);
  },
  onError: (ev, { values, errors }) => {
    ev.preventDefault();
  },
  onSuccess: (ev, { values }) => {
    ev.preventDefault();
  },
  onSubmit: ev => {
    ev.preventDefault();
    console.log(ev);
  }
};

export default function App() {
  const { values, errors, inputProps, onSubmit } = useFormless(options);

 return (
    <section>
      <form onSubmit={onSubmit}>
        <div>
          <label htmlFor="name">name</label>
          <input
            id="name"
            type="text"
            {...inputProps("name")}
            value={values.name}
          />
          <p>{errors.name}</p>
        </div>
        <div>
          <label htmlFor="password">password</label>
          <input
            id="password"
            type="password"
            {...inputProps("password")}
            value={values.password}
          />
          <p>{errors.password}</p>
        </div>
        <input type="submit" value="Login" />
      </form>
    </section>
  );
}

We have the options object with the options.

initialValues has the initial values of the form.

validate is a function that returns an error object after validation.

The returned object should have the keys with the input names and values being the error message.

onError , onSuccess and onSubmit are handlers that are run when those events are emitted.

We pass in the whole object to the useFormless hook.

It returns an object with the variables we can use in our form.

inputProps pass in the input elements.

onSubmit is the submit handler.

errors has the error messages.

values has the input values for each field.

Conclusion

React-use is a versatile hooks library.

React-useFormless lets us create forms easily with our React app.

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 *