Categories
React Answers

How to detect browser in React?

To detect browser in React, we use the react-device-detect package.

To install it, we run

npm i react-device-detect

Then we use it by writing

import { isMobile } from "react-device-detect";

function App() {
  if (isMobile) {
    return <div> This content is available only on mobile</div>;
  }
  return <div> ...content </div>;
}

to use the isMobile variable to check if the content is displayed in the mobile browser.

Categories
React Answers

How to mock the window size changing for a React component test with JavaScript?

To mock the window size changing for a React component test with JavaScript, we can mock the window.screen.width property.

For instance, we write

jest.spyOn(window.screen, "width", "get").mockReturnValue(1000);

to call jest.spyOn to mock the window.screen.width getter property.

And we call mockReturnValue to set its return value to 1000.

Categories
React Answers

How to highlight text using React?

To highlight text using React, we can use the react-highlighter module.

To install it, we run

npm i react-highlighter

Then we write

const Highlight = require("react-highlighter");

<Highlight search="brown">
  The quick brown fox jumps over the lazy dog
</Highlight>

to use the Highlight component to highlight 'brown' in 'The quick brown fox jumps over the lazy dog'.

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.