Categories
React Answers

How to detect whether input element is focused within React?

To detect whether input element is focused within React, we check the activeElement property.

For instance, we write

//...
const Component = () => {
  const searchInput = React.useRef(null);
  //...
  if (document.activeElement === searchInput.current) {
    // do something
  }

  return <input type="text" ref={searchInput} />;
};

to create a ref with useRef and assign it to the input.

Then we check if the input is focused with document.activeElement === searchInput.current.

document.activeElement is the element currently focused on and searchInput.current is the input with the ref.

Categories
React Answers

How to fix ‘Matched leaf route at location “/” does not have an element’ error with React Router 6?

To fix ‘Matched leaf route at location "/" does not have an element’ error with React Router 6, we set the element prop to the component we want to render when we go to the URL.

For instance, we write

<Route path="/" element={<Home />}></Route>;

to add a Route component with the element prop set to the Home component.

Then when we go to /, we see the Home component rendered.

Categories
React Answers

How to fix “typeerror: cannot read properties of undefined (reading ‘pathname’)” with React Router?

To fix "typeerror: cannot read properties of undefined (reading ‘pathname’)" with React Router, we should wrap the Router component around our app.

For instance, we write

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";

const Main = () => <h1>Hello world</h1>;

ReactDOM.render(
  <Router>
    <Route path="/" component={Main} />
  </Router>,
  document.getElementById("app")
);

to wrap the Router component around our Route components.

Then we can get the pathname property value using this.props.history.location.pathname property in any component set as the value of the component prop in the Route component.

This is because the Router component injects the history prop into the route components.

Categories
React Answers

How to Download PDF in React.js?

To download PDF 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.

Categories
React Answers

How to pass state to another component with react-router-dom v6 useNavigate hook?

To pass state to another component with react-router-dom v6 useNavigate hook, we can call navigate with an object as the 2nd argument.

For instance, we write

import { Link, useNavigate } from "react-router-dom";

const ComponentA = (props) => {
  const navigate = useNavigate();

  const toComponentB = () => {
    navigate("/componentB", { state: { id: 1, name: "sabaoon" } });
  };

  return (
    <>
      <div>
        <a onClick={() => toComponentB()}>Component B</a>
      </div>
    </>
  );
};

export default ComponentA;

to call navigate with the "/componentB" URL path and an object that we want to pass to the component that renders when we go to /componentB.

Then in ComponentB, which is rendered when we go to /componentB, we get the values from the useLocation hook by writing

import { useLocation } from "react-router-dom";

const ComponentB = () => {
  const location = useLocation();

  return (
    <>
      <div>{location.state.name}</div>
    </>
  );
};

export default ComponentB;

We call the useLocation hook to return the object that we passed in as the 2nd argument of navigate in ComponentA.

And then we get the properties from the location object.