Categories
React Answers

How to fix the Formik form does not fire submit on return key press issue with React?

Sometimes, we want to fix the Formik form does not fire submit on return key press issue with React.

In this article, we’ll look at how to fix the Formik form does not fire submit on return key press issue with React.

How to fix the Formik form does not fire submit on return key press issue with React?

To fix the Formik form does not fire submit on return key press issue with React, we can add an input with the type attribute set to submit.

For instance, we write:

import React from "react";
import { object, string } from "yup";
import { Formik } from "formik";

const validationSchema = object().shape({
  email: string()
    .email("Please enter a valid email address")
    .required("Email is a required field"),
  password: string().min(8).required("Password is a required field")
});

export default function App() {
  return (
    <Formik
      initialValues={{
        email: "",
        password: ""
      }}
      onSubmit={(values) => {
        console.log(values);
      }}
      validationSchema={validationSchema}
    >
      {(props) => {
        const {
          values,
          handleChange,
          handleBlur,
          handleSubmit,
          errors
        } = props;
        return (
          <form onSubmit={handleSubmit}>
            <input
              value={values.email}
              onChange={handleChange}
              onBlur={handleBlur}
              name="email"
            />
            <p>{errors?.email}</p>
            <input
              value={values.password}
              onChange={handleChange}
              onBlur={handleBlur}
              name="password"
              type="password"
            />
            <p>{errors?.password}</p>
            <input type="submit" />
          </form>
        );
      }}
    </Formik>
  );
}

We define the validationSchema object with yup.

It checks for email and password requirements and return validation error messages if the values are invalid.

Then we add the form by wrapping a form element in the Formik component.

We set the initial values with the initialValues prop.

And we set the onSubmit prop to the submit event handler.

The values parameter has all the entered values.

And we set the validationSchema prop to the validationSchema object so we can use it for form validation.

Next, we add a render prop inside the Formik component which returns a form element with the props of the render prop function used throughout the form.

We set the value prop of each input to the values in the value prop property.

And we set onChange and onBlur to the functions in the prop.

Also, we set the name attribute for each input to match the field names in validationSchema so the validation can be done.

We display the form validation errors from the errors object.

Finally, we add an input with the type attribute set to submit to trigger run the submit event handler when the form values are all valid.

Therefore, when we type in valid values in each field, we see the values logged.

Conclusion

To fix the Formik form does not fire submit on return key press issue with React, we can add an input with the type attribute set to submit.

Categories
React Answers

How to use the useCallback hook for map rendering with React?

Sometimes, we want to use the useCallback hook for map rendering with React.

In this article, we’ll look at how to use the useCallback hook for map rendering with React.

How to use the useCallback hook for map rendering with React?

To use the useCallback hook for map rendering with React, we can pass in the function we want to update when a state or prop updates as the useCallback callback.

For instance, we write:

import React, { useCallback } from "react";

const ExpensiveComponent = ({ onEvent }) => {
  //...
  return <p>expensive</p>;
};

const MappedComponent = ({ id }) => {
  const onEvent = useCallback(() => console.log(id), []);
  return <ExpensiveComponent onEvent={onEvent} />;
};

const FrequentlyRerendersMap = ({ ids }) => {
  return ids.map((id) => {
    return <MappedComponent key={id} id={id} />;
  });
};

export default function App() {
  return <FrequentlyRerendersMap ids={[1, 2, 3]} />;
}

We have the ExpensiveComponent that takes the onEvent function prop.

Then we define the MappedComponent that defines the onEvent function which is defined with the useCallback hook with a callback.

Then callback is run when onEvent is called.

Next, we have the FrequentlyRerendersMap component that renders an array of MappedComponent with the ids.map method.

Finally, we render FrequentlyRerendersMap in App.

Conclusion

To use the useCallback hook for map rendering with React, we can pass in the function we want to update when a state or prop updates as the useCallback callback.

Categories
React Answers

How to store the state of radio groups in React using react-hook-form?

Sometimes, we want to store the state of radio groups in React using react-hook-form.

In this article, we’ll look at how to store the state of radio groups in React using react-hook-form.

How to store the state of radio groups in React using react-hook-form?

To store the state of radio groups in React using react-hook-form, we can set the defaultChecked prop to the initial checked value for each radio button.

For instance, we write:

import React, { useState } from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const [state] = useState({ data: { checked: "1" } });
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm();
  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="vehicles">
        How many vehicles do you own?
        <br />
        <input
          type="radio"
          name="vehicles"
          value="1"
          {...register("vehicles", { required: true })}
          className="radio"
          defaultChecked={state.data.checked === "1"}
        />
        <label>1</label>
        <input
          type="radio"
          name="vehicles"
          value="2"
          {...register("vehicles", { required: true })}
          className="radio"
          defaultChecked={state.data.checked === "2"}
        />
        <label>2</label>
        {errors.vehicles && (
          <div className="form_error">Number of Vehicles is required</div>
        )}
      </label>

      <input type="submit" />
    </form>
  );
}

We use the useForm hook to return an object with various properties we use to create our form.

Next, we define the onSubmit function that we use as the form submit handler.

Then we add our form element with the onSubmit prop set to handleSubmit(onSubmit) which only runs when the form values are all valid.

Next, we add inputs that we register as react-hook-form fields with register.

And we set the defaultChecked prop to set the condition for which the radio button is checked.

The initial checked value is checked according to the initial state value.

Therefore, 1 should be selected initially.

Conclusion

To store the state of radio groups in React using react-hook-form, we can set the defaultChecked prop to the initial checked value for each radio button.

Categories
React Answers

How to add a PowerPoint viewer into a React component?

Sometimes, we want to add a PowerPoint viewer into a React component.

In this article, we’ll look at how to add a PowerPoint viewer into a React component.

How to add a PowerPoint viewer into a React component?

To add a PowerPoint viewer into a React component, we can add a iframe that shows the PowerPoint slide’s with Microsoft’s online PowerPoint viewer.

For instance, we write:

import React from "react";

const linkToPPTFile =
  "https://scholar.harvard.edu/files/torman_personal/files/samplepptx.pptx";

export default function App() {
  return (
    <>
      <iframe
        src={`https://view.officeapps.live.com/op/embed.aspx?src=${linkToPPTFile}`}
        width="100%"
        height="600px"
        frameBorder="0"
        title="slides"
      ></iframe>
    </>
  );
}

We want to show the PowerPoint presentation that’s located in the URL assigned to linkToPPTFile .

To show the slides, we add an iframe with src set to https://view.officeapps.live.com/op/embed.aspx?src=${linkToPPTFile}.

We also set the width and height to set the dimensions.

And we set the frameBorder to 0 to remove the iframe border.

Conclusion

To add a PowerPoint viewer into a React component, we can add a iframe that shows the PowerPoint slide’s with Microsoft’s online PowerPoint viewer.

Categories
React Answers

How to create a number input with no negative, decimal, or zero value values with React?

Sometimes, we want to create a number input with no negative, decimal, or zero value values with React.

In this article, we’ll look at how to create a number input with no negative, decimal, or zero value values with React.

How to create a number input with no negative, decimal, or zero value values with React?

To create a number input with no negative, decimal, or zero value values with React, we can create our own input component.

For instance, we write:

import React, { useState } from "react";

const PositiveInput = () => {
  const [value, setValue] = useState("");

  const onChange = (e) => {
    const value = e.target.value.replace(/[^\d]/, "");

    if (+value !== 0) {
      setValue(value);
    }
  };

  return <input type="text" value={value} onChange={onChange} />;
};

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

We create the PositiveInput component that lets us only enter positive numbers.

In the component, we have the value state.

And we define the onChange function that sets the value state by getting the value from the input.

And we replace all the non numerical values in the input value with empty strings.

This is done with const value = e.target.value.replace(/[^\d]/, "");.

Then if value isn’t 0, then we call setValue to set value.

Next, we set the value prop of the input to value and the onChange prop to onChange.

Finally, we add the input to App.

Conclusion

To create a number input with no negative, decimal, or zero value values with React, we can create our own input component.