Categories
React Answers

How to specify null prop type in React?

Sometimes, we want to specify null prop type in React.

In this article, we’ll look at how to specify null prop type in React.

How to specify null prop type in React?

To specify null prop type in React, we can set null as the default prop value.

For instance, we write:

import React from "react";
import PropTypes from "prop-types";

const MyComponent = ({ item }) => {
  return item;
};

MyComponent.propTypes = {
  item: PropTypes.string.isRequired
};

MyComponent.defaultProps = {
  item: null
};

export default function App() {
  return (
    <div>
      <MyComponent item="foo" />
      <MyComponent />
    </div>
  );
}

We create the MyComponent component accepts the item prop.

We set item‘s type to be a string and is required.

And then we specify that its default value is null so it can be set to null when nothing is set for item.

As a result, we see ‘foo’ rendered on the screen since we set item to 'foo' in the first MyComponent instance.

Conclusion

To specify null prop type in React, we can set null as the default prop value.

Categories
React Answers

How to change the background color of the body element in React?

Sometimes, we want to change the background color of the body element in React.

In this article, we’ll look at how to change the background color of the body element in React.

How to change the background color of the body element in React?

To change the background color of the body element in React, we can use the React Helmet package.

For instance, we write:

import React from "react";
import { Helmet } from "react-helmet";

export default function App() {
  return (
    <div>
      <Helmet>
        <style>{"body { background-color: orange; }"}</style>
      </Helmet>
      <p>hello world</p>
    </div>
  );
}

We put the style element inside the Helmet component so that it’s rendered in the head element.

Then we use "body { background-color: orange; }" to set the background color of the body element.

Therefore, we should see that the background color of the page is orange.

Conclusion

To change the background color of the body element in React, we can use the React Helmet package.

Categories
React Answers

How to show or hide React components without losing their internal state?

Sometimes, we want to show or hide React components without losing their internal state.

In this article, we’ll look at how to show or hide React components without losing their internal state.

How to show or hide React components without losing their internal state?

To show or hide React components without losing their internal state, we can set the display CSS property to 'none' to hide the component.

For instance, we write:

import React, { useState } from "react";

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <>
      <button onClick={() => setCount((c) => c + 1)}>increment</button>
      <p>{count}</p>
    </>
  );
};

const Counter2 = () => {
  const [count, setCount] = useState(0);

  return (
    <>
      <button onClick={() => setCount((c) => c + 2)}>increment</button>
      <p>{count}</p>
    </>
  );
};

export default function App() {
  const [toggle, setToggle] = useState(true);

  return (
    <>
      <button onClick={() => setToggle((t) => !t)}>toggle</button>
      <div style={{ display: toggle ? "none" : "block" }}>
        <Counter />
      </div>
      <div style={{ display: toggle ? "block" : "none" }}>
        <Counter2 />
      </div>
    </>
  );
}

We have the Counter and Counter2 components that lets us set the count state by clicking on the increment button.

To keep the count value when we show and hide the 2 components, we wrap divs around the 2 components.

And then we set the display CSS property to 'none' or 'block' depending on the toggle state value.

And then we set the object with the display property as the value of the style prop of each div.

This way, the components won’t be taken out of the DOM when we hide them so their states are kept.

Conclusion

To show or hide React components without losing their internal state, we can set the display CSS property to 'none' to hide the component.

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.