Categories
React Answers

How to upload image with React dropzone?

Sometimes, we want to upload image with React dropzone.

In this article, we’ll look at how to upload image with React dropzone.

How to upload image with React dropzone?

To upload image with React dropzone, we can define a drop event handler function and upload the selected file inside the handler.

For instance, we write:

import React, { useCallback } from "react";
import { useDropzone } from "react-dropzone";

export default function App() {
  const onDrop = useCallback(async (acceptedFiles) => {
    const formData = new FormData();
    const [file] = acceptedFiles;
    formData.append("file", file);

    await fetch("https://httpbin.org/post", {
      method: "POST",
      body: formData
    });
  }, []);
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  return (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      {isDragActive ? (
        <p>Drop the files here ...</p>
      ) : (
        <p>Drag 'n' drop some files here, or click to select files</p>
      )}
    </div>
  );
}

We define the onDrop function with the useCallback hook.

We pass in an async function that gets the file from acceptedFiles.

Then we create a new form data object with the FormData constructor.

And we call append with the file as the value a form data entry.

Then we call fetch with the URL and an object with the body set to formData to do the upload.

Next, we call the useDropzone hook to return an object with a function of properties that we either call or render.

We call getRootProps and getInputProps and spread the returned object as props.

And we get whether we’re dragging a file to the drop zone with isDragActive.

Now when we drop a file into the drop zone, a request should be made to do the upload.

Conclusion

To upload image with React dropzone, we can define a drop event handler function and upload the selected file inside the handler.

Categories
React Answers

How to use React-datepicker with a Formik form?

Sometimes, we want to use React-datepicker with a Formik form.

In this article, we’ll look at how to use React-datepicker with a Formik form.

How to use React-date picker with a Formik form?

To use React-date picker with a Formik form, we can create a date picker component that renders the React-datepicker component.

We use the useFormikContext hook to let us add form validation with Formik to the React-datepicker component.

For instance, we write:

import React from "react";
import { Formik, useField, useFormikContext } from "formik";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

const DatePickerField = ({ ...props }) => {
  const { setFieldValue } = useFormikContext();
  const [field] = useField(props);
  return (
    <DatePicker
      {...field}
      {...props}
      selected={(field.value && new Date(field.value)) || null}
      onChange={(val) => {
        setFieldValue(field.name, val);
      }}
    />
  );
};
export default function App() {
  return (
    <div>
      <Formik
        initialValues={{ date: "" }}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            console.log(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 500);
        }}
      >
        {(props) => {
          const { dirty, isSubmitting, handleSubmit, handleReset } = props;
          return (
            <form onSubmit={handleSubmit}>
              <DatePickerField name="date" />
              <button
                type="button"
                className="outline"
                onClick={handleReset}
                disabled={!dirty || isSubmitting}
              >
                Reset
              </button>
              <button type="submit" disabled={isSubmitting}>
                Submit
              </button>
            </form>
          );
        }}
      </Formik>
    </div>
  );
}

We define the DatePickerField component that takes the props from the props object.

In the component, we call useFormikContext to return an object with the setFieldValue method.

Then we call the useField hook with props to create the field object which we use to set the selected state and use the field.name property to get the field’s name.

We call setFieldValue to set the field’s value by passing in the field name string and the selected value.

Then to use DatePickerField in a Formik form, we put it inside the render prop’s return value.

useFormikContext and useField returned all the values required to let Formik handle value change and form validation.

We also set initialValues to an object with the name of the field as the property names.

And we set the name prop of DatePickerField to the same value as the property value so validation and the value can be set as the value of the property with the same name.

Conclusion

To use React-date picker with a Formik form, we can create a date picker component that renders the React-datepicker component.

We use the useFormikContext hook to let us add form validation with Formik to the React-datepicker component.

Categories
React Answers

How to add select option with object as the value attribute value with React?

Sometimes, we want to add select option with object as the value attribute value with React.

In this article, we’ll look at how to add select option with object as the value attribute value with React.

How to add select option with object as the value attribute value with React?

To add select option with object as the value attribute value with React, we can set the value attribute to the index and then select the object from the index from the options array.

For instance, we write:

import React, { useState } from "react";

const options = [{ name: "apple" }, { name: "orange" }, { name: "grape" }];

export default function App() {
  const [option, setOption] = useState({});
  console.log(option);

  const handleChange = (e) => {
    setOption(options[+e.target.value]);
  };

  return (
    <select onChange={handleChange}>
      {options.map((option, index) => (
        <option key={index} value={index}>
          {option.name}
        </option>
      ))}
    </select>
  );
}

We have an array of options that we render as options in the select drop down.

To do the rendering, we call options.map with a callback that returns the option elements.

We set the value attribute value to index so we can select the object from the list once we selected an option.

Next, we define the handleChange function that calls setOption with options[+e.target.value] to set option to the selected object from options.

e.target.value has the value attribute value of the option element selected.

Therefore, from the console log, we see the object that corresponds to the options we selected from the drop down.

Conclusion

To add select option with object as the value attribute value with React, we can set the value attribute to the index and then select the object from the index from the options array.

Categories
React Answers

How to add a header and footer into a layout component with React?

Sometimes, we want to add a header and footer into a layout component with React.

In this article, we’ll look at how to add a header and footer into a layout component with React.

How to add a header and footer into a layout component with React?

To add a header and footer into a layout component with React, we can add the header and footer into the layout component.

For instance, we write:

import React from "react";

const Header = () => <header>header</header>;

const Footer = () => <footer>footer</footer>;

const Layout = ({ children }) => {
  return (
    <div>
      <Header />
      {children}
      <Footer />
    </div>
  );
};

export default function App() {
  return <Layout>hello world</Layout>;
}

We define the Header and Footer components to render content for the header and footer of the layout respectively.

Then we define the Layout component to render the Header and Footer around the children prop.

children has the content between the opening and closing tags of Layout.

Therefore, we see:

header
hello world
footer

rendered on the screen.

Conclusion

To add a header and footer into a layout component with React, we can add the header and footer into the layout component.

Categories
React Answers

How to fix the throttle mousemove event keep throwing event.persist() error issue with React?

Sometimes, we want to fix the throttle mousemove event keep throwing event.persist() error issue with React.

In this article, we’ll look at how to fix the throttle mousemove event keep throwing event.persist() error issue with React.

How to fix the throttle mousemove event keep throwing event.persist() error issue with React?

To fix the throttle mousemove event keep throwing event.persist() error issue with React, we can use the throttle Lodash method with the event.persist method.

For instamce, we can write:

import React, { useMemo } from "react";
import { throttle } from "lodash";

export default function App() {
  const onMouseMove = useMemo(() => {
    const throttled = throttle((e) => console.log(e.screenX), 300);
    return (e) => {
      e.persist();
      return throttled(e);
    };
  }, []);

  return (
    <div>
      <div onMouseMove={onMouseMove}>Content</div>
    </div>
  );
}

to define the onMouseMove function that is defined by calling the useMemo hook with a function that does the throttling with Lodash throttle.

We throttle the (e) => console.log(e.screenX) to run once every 300 milliseconds.

Then we return a function that calls e.persist to persist the event.

And then we throttled mousemove event handler that we created with throttle by calling it with e.

Now when we move our move over the div, we should no longer see errors when calling event.persist.

Conclusion

To fix the throttle mousemove event keep throwing event.persist() error issue with React, we can use the throttle Lodash method with the event.persist method.