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.

Categories
React Answers

How to Download File in React.js?

To download a file with React.js, we can add the download attribute to an anchor element.

For instance, we can write:

import React from "react";

export default function App() {
  return (
    <div>
      <a
        href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
        download
      >
        Click to download
      </a>
    </div>
  );
}

We just add the download prop to do the download.

If we don’t want to use an anchor element, we can also use the file-saver package to download our file.

To install it, we run:

npm i file-saver

Then we can call the saveAs function from the package by writing:

import React from "react";
import { saveAs } from "file-saver";

export default function App() {
  const saveFile = () => {
    saveAs(
      "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
      "example.pdf"
    );
  };
  return (
    <div>
      <button onClick={saveFile}>download</button>
    </div>
  );
}

The first argument is the URL to download and the 2nd argument is the file name of the downloaded file.