Categories
React Answers

How to properly use Formik’s setStatus method?

Sometimes, we want to properly use Formik’s setStatus method.

In this article, we’ll look at how to properly use Formik’s setStatus method.

How to properly use Formik’s setStatus method?

To properly use Formik’s setStatus method, we can call it in the submit handler.

For instance, we write:

import React from "react";
import { Formik } from "formik";

export default function App() {
  return (
    <Formik
      initialValues={{ email: "", password: "" }}
      validate={(values) => {
        const errors = {};
        if (!values.email) {
          errors.email = "Required";
        } else if (
          !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
        ) {
          errors.email = "Invalid email address";
        }
        return errors;
      }}
      onSubmit={(values, { setSubmitting, setStatus }) => {
        setStatus();
        setTimeout(() => {
          console.log(JSON.stringify(values, null, 2));
          setSubmitting(false);
          setStatus("success");
        }, 1000);
      }}
    >
      {({
        values,
        errors,
        touched,
        handleChange,
        handleBlur,
        handleSubmit,
        isSubmitting,
        status
      }) => (
        <form onSubmit={handleSubmit}>
          {status}
          <input
            type="email"
            name="email"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.email}
          />
          {errors.email && touched.email && errors.email}
          <input
            type="password"
            name="password"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.password}
          />
          {errors.password && touched.password && errors.password}
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </form>
      )}
    </Formik>
  );
}

We have a form that we create with the Formik component.

We have the validate prop set to a function that returns any errors in the input values.

The onSubmit prop is set to a function that calls setStatus to set the status property in the render prop’s object parameter.

We display status above the inputs.

The values property has the input values of each field.

We set the name attribute of each input to set the properties with the names of the names attributes of the values object to the input value of the field with the given name attribute.

Now when the onSubmit function is run, we should see ‘success’ displayed on the left of the form.

Conclusion

To properly use Formik’s setStatus method, we can call it in the submit handler.

Categories
React Answers

How to forward multiple refs with React?

Sometimes, we want to forward multiple refs with React.

In this article, we’ll look at how to forward multiple refs with React.

How to forward multiple refs with React?

To forward multiple refs with React, we can pass in the refs in an object.

For instance, we write:

import React, { useRef } from "react";

const Child = React.forwardRef((props, ref) => {
  const { ref1, ref2 } = ref.current;
  console.log(ref1, ref2);

  return (
    <>
      <p ref={ref1}>foo</p>
      <p ref={ref2}>bar</p>
    </>
  );
});

export default function App() {
  const ref1 = useRef();
  const ref2 = useRef();
  const ref = useRef({ ref1, ref2 });

  return <Child ref={ref} />;
}

We have the Child component that accepts refs since we created it by calling forwardRef with the component function.

In the function, we destructure the refs we pass in by using:

const { ref1, ref2 } = ref.current;

Then we assign ref1 and ref2 to the p elements.

In App, we create the refs with the useRef hook.

We create ref by calling useRef with an object created from the existing refs.

And finally, we set the ref prop of the Child to ref.

Therefore, from the console log, we can see ref1 and ref2‘s current property are assigned to the paragraph elements in Child.

Conclusion

To forward multiple refs with React, we can pass in the refs in an object.

Categories
React Answers

How to get a rendered component height with React?

Sometimes, we want to get a rendered component height with React.

In this article, we’ll look at how to get a rendered component height with React.

How to get a rendered component height with React?

To get a rendered component height with React, we can use the element’s clientHeight property.

For instance, we write:

import React, { useEffect, useRef } from "react";

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

  useEffect(() => {
    console.log(ref.current?.clientHeight);
  }, []);

  return <div ref={ref}>hello world</div>;
}

We assign the ref ref to the ref prop of the div.

Then we call useEffect with a callback and an empty array to get the element’s height when the component mounts.

In the useEffect callback, we use ref.current?.clientHeight to get the div’s height in pixels.

Conclusion

To get a rendered component height with React, we can use the element’s clientHeight property.

Categories
React Answers

How to get the value of an input from the input’s ref in a React component?

Sometimes, we want to get the value of an input from the input’s ref in a React component.

In this article, we’ll look at how to get the value of an input from the input’s ref in a React component.

How to get the value of an input from the input’s ref in a React component?

To get the value of an input from the input’s ref in a React component, we can use the value attribute.

For instance, we write:

import React, { useRef } from "react";

export default function App() {
  const cityInput = useRef();

  const onSubmit = (e) => {
    e.preventDefault();
    console.log(cityInput.current.value);
  };

  return (
    <form onSubmit={onSubmit}>
      <input type="text" placeholder="Enter City Name" ref={cityInput} />
      <button>Go!</button>
    </form>
  );
}

We create a cityInput ref with the useRef hook.

Then we define the onSubmit function that gets the input’s value by using cityInput.current.value.

We call e.preventDefault to stop the default server side submission behavior.

Next, we set the ref prop of the input to cityInput so that cityInput.current is set to the input element.

Finally, we set the onSubmit prop to onSubmit to run it when we click Go.

Conclusion

To get the value of an input from the input’s ref in a React component, we can use the value attribute.

Categories
React Answers

How to get select element’s value in react-bootstrap?

Sometimes, we want to get select element’s value in react-bootstrap.

In this article, we’ll look at how to get select element’s value in react-bootstrap.

How to get select element’s value in react-bootstrap?

To get select element’s value in react-bootstrap, we can set the onChange prop to a function that gets the selected value.

For instance, we write:

import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Form } from "react-bootstrap";

export default function App() {
  const [val, setVal] = useState();
  console.log(val);

  return (
    <Form.Select value={val} onChange={(e) => setVal(e.target.value)}>
      <option>Open this select menu</option>
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </Form.Select>
  );
}

We create the val state with the useState hook.

Then we add a select drop down by adding the Form.Select component.

Next, we set onChange of the Form.Select component to a function that calls setVal with e.target.value to set val to the value attribute value of the selected option element.

As a result, we should see the selected value logged when we change the option we select from the drop down.

Conclusion

To get select element’s value in react-bootstrap, we can set the onChange prop to a function that gets the selected value.