Categories
React Answers

How to Display a Loading Screen While the DOM is Rendering with React?

Sometimes, we want to display a loading screen while the DOM is rendering with React.

In this article, we’ll look at how to display a loading screen while the DOM is rendering with React.

Display a Loading Screen While the DOM is Rendering with React

To display a loading screen while the DOM is rendering with React, we can add a loading state into our React component.

Then we can display what we want depending on whether the component is done loading or not.

For example, we can write:

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

export default function App() {
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setLoading(false);
    }, 2000);
  }, []);

  return <div>{loading ? "loading..." : "hello"}</div>;
}

We have the loading state that we created with the useState hook.

Then we call the useEffect hook with a callback that calls setLoading with false to set loading to false .

And in the return statement, we return 'loading...' is loading is true and 'hello' otherwise.

Conclusion

To display a loading screen while the DOM is rendering with React, we can add a loading state into our React component.

Then we can display what we want depending on whether the component is done loading or not.

Categories
React Answers

How to Get the Viewport or Window Height in React?

Sometimes, we want to get the viewport or window height with React.

In this article, we’ll look at how to get the viewport or window height with React.

Get the Viewport or Window Height in React

To get the viewport or window height with React, we can add the resize listener into our React app.

For instance, we can write:

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

const getWindowDimensions = () => {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height
  };
};

const useWindowDimensions = () => {
  const [windowDimensions, setWindowDimensions] = useState(
    getWindowDimensions()
  );

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

  window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return windowDimensions;
};

export default function App() {
  const { height, width } = useWindowDimensions();

  return (
    <div>
      width: {width} x height: {height}
    </div>
  );
}

to add the useWindowDimensions hook that calls the useEffect hook with a callback that adds the resize event on window into our app.

We call window.addEventListener to add the resize event listener.

And then we call getWindowDimensions to get the window dimensions.

We get the window.innerHeight to get the height of the viewport or window.

And innerWidth gets the width of it.

We call setWindowDimensions on with the object returned by getWindowDimensions .

Then we use the useWindowDimensions hook in our App component to render the height and width .

Now when we resize the viewport, we see the dimension numbers change.

Conclusion

To get the viewport or window height with React, we can add the resize listener into our React app.

Categories
React Answers

How to Add the ‘for’ Attribute of the Label Element in React?

Sometimes, we want to add the for attribute to a label element to associate it with a form field in React.

In this article, we’ll look at how to add the for attribute to a label element to associate it with a form field in React.

Add the ‘for’ Attribute of the Label Element in React

To add the for attribute to a label element to associate it with a form field in React, we can set the htmlFor attribute for the label.

For instance, we can write:

import React from "react";

export default function App() {
  return (
    <div>
      <label htmlFor="name">name</label>
      <input id="name" name="name" />
    </div>
  );
}

to add the htmlFor attribute to the label element.

We set htmlFor to name so it’ll be rendered as the label element with the for attribute set to name .

Conclusion

To add the for attribute to a label element to associate it with a form field in React, we can set the htmlFor attribute for the label.

Categories
React Answers

How to Listen for Key Press for Document in React.js?

Sometimes, we want to listen for keypresses on the whole document in React.js.

In this article, we’ll look at how to listen for keypresses on the whole document in React.js.

Listen for Key Press for Document in React.js

To listen for keypresses on the whole document in React.js, we can call addEventListener on document in the useEffect hook.

For instance, we can write:

import React, { useEffect, useRef } from "react";
const ESCAPE_KEYS = ["27", "Escape"];

const useEventListener = (eventName, handler, element = window) => {
  const savedHandler = useRef();

  useEffect(() => {
    savedHandler.current = handler;
  }, [handler]);

  useEffect(() => {
    const eventListener = (event) => savedHandler.current(event);
    element.addEventListener(eventName, eventListener);
    return () => {
      element.removeEventListener(eventName, eventListener);
    };
  }, [eventName, element]);
};

export default function App() {
  const handler = ({ key }) => {
    if (ESCAPE_KEYS.includes(String(key))) {
      console.log("Escape key pressed!");
    }
  };

  useEventListener("keydown", handler);

  return <span>hello world</span>;
}

We create the useEventListener hook that takes the eventName , handler , and element parameters.

eventName is the event name.

handler is the event handler function.

element is the element we call addEventListener on.

In the first useEffect callback, we set the handler as the current value of the ref to cache it.

Next, in the 2nd useEffect callback, we call element.addEventListener with the eventName and handler to listen to the eventName event.

Then we use the useEventHandler hook in App by calling it with 'keydown' and the handler function to listen to the keydown event.,

Then we get key property in handler to check which key is pressed.

Conclusion

To listen for keypresses on the whole document in React.js, we can call addEventListener on document in the useEffect hook.

Categories
React Answers

How to Retrieve the Value From a Muti-Select Element in React?

Sometimes, we want to retrieve the value from a multi-select element in React.

In this article, we’ll look at how to retrieve the value from a multi-select element in React.

Retrieve the Value From a Muti-Select Element in React

To retrieve the value from a multi-select element in React, we can get the selected values from the e.target.selectedOptions property.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [values, setValue] = useState([]);
  const handleChange = (e) => {
    const value = [...e.target.selectedOptions].map((option) => option.value);
    setValue(value);
  };

  return (
    <div>
      <select onChange={handleChange} multiple>
        <option value={1}>apple</option>
        <option value={2}>orange</option>
        <option value={3}>grape</option>
      </select>
      <p>{values.toString()}</p>
    </div>
  );
}

We defined the values state with the useState hook.

Then we defined the handleChange function that spreads the e.target.selectedOptions property into an array.

And then we call map to get the value property from each selected item.

Finally, we add the select element with the multiple prop to add a multi-select dropdown.

And we display the values below that.

Now when we select from the multi-select box, we see the value prop of the selected option element displayed.

Conclusion

To retrieve the value from a multi-select element in React, we can get the selected values from the e.target.selectedOptions property.