Categories
React Answers

How to get the onBlur method fire only when the focus gets out of an element with React?

Sometimes, we want to get the onBlur method fire only when the focus gets out of an element with React.

In this article, we’ll look at how to get the onBlur method fire only when the focus gets out of an element with React.

How to get the onBlur method fire only when the focus gets out of an element with React?

To get the onBlur method fire only when the focus gets out of an element with React, we can check if the blur event is emitted by an element outside the given element with the e.currentTarget.contains method.

For instance, we write:

import React from "react";

export default function App() {
  const onBlur = (e) => {
    if (!e.currentTarget.contains(e.relatedTarget)) {
      console.log("blur event");
    }
  };

  return (
    <div>
      <h1>Table</h1>
      <table onBlur={onBlur}>
        <thead>
          <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Publisher</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>1</td>
            <td>
              <input type="text" />
            </td>
            <td>
              <input type="text" />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

We define the onBlur function that checks if the e.relatedTarget is inside the e.currentTarget with contains.

e.currentTarget is the element being blurred.

And e.relatedTarget is the element that received the focus.

Therefore, if the element that received the focus isn’t the element inside the table, then we know the focus is outside the table.

As a result, only when we focus away from the last input then the onBlur function will be run.

Conclusion

To get the onBlur method fire only when the focus gets out of an element with React, we can check if the blur event is emitted by an element outside the given element with the e.currentTarget.contains method.

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.