Categories
React Answers

How to create constants file with React?

Sometimes, we want to create constants file with React.

In this article, we’ll look at how to create constants file with React.

How to create constants file with React?

To create constants file with React, we can create a JavaScript file with variables exported.

For instance, we write

fileWithConstants.js

export const ACTION_INVALID = "This action is invalid!";
export const CONSTANT_NUMBER_1 = "hello I am a constant";
export const CONSTANT_NUMBER_2 = "hello I am also a constant";

to export the ACTION_INVALID, CONSTANT_NUMBER_1 and CONSTANT_NUMBER_2 constants in a file.

Then we can use them by writing

import * as consts from "path/to/fileWithConstants";

const errorMsg = consts.ACTION_INVALID;

to import all the contents of fileWithConstants.js that are export and reference ACTION_INVALID with consts.ACTION_INVALID.

How to create constants file with React?

To create constants file with React, we can create a JavaScript file with variables exported.

Categories
React Answers

How to trigger onChange if input value is changing by state with React?

Sometimes, we want to trigger onChange if input value is changing by state with React.

In this article, we’ll look at how to trigger onChange if input value is changing by state with React.

How to trigger onChange if input value is changing by state with React?

To trigger onChange if input value is changing by state with React, we can watch for state change with the useEffect hook.

For instance, we write

const MyInputComponent = () => {
  const [numberValue, setNumberValue] = useState(0);
  const numberInput = useRef(null);

  useEffect(() => {
    numberInput.current.dispatchEvent(
      new Event("change", {
        detail: {
          newValue: numberValue,
        },
        bubbles: true,
        cancelable: true,
      })
    );
  }, [numberValue]);

  return (
    <>
      <input
        type="number"
        value={numberValue}
        ref={numberInput}
        inputMode="numeric"
        onChange={(e) => setNumberValue(e.target.value)}
      />
    </>
  );
};

to add an input that’s bound to the numberValue state with the onChange and value props.

value is set to numberValue to display numberValue as the input value.

onChange is set to (e) => setNumberValue(e.target.value) to set the numberValue state to a value.

Then we call useEffect hook with [numberValue] to call the useEffect callback when the numberValue state changes.

Conclusion

To trigger onChange if input value is changing by state with React, we can watch for state change with the useEffect hook.

Categories
React Answers

How to get a div’s offsetTop positions in React?

Sometimes, we want to get a div’s offsetTop positions in React.

In this article, we’ll look at how to get a div’s offsetTop positions in React.

How to get a div’s offsetTop positions in React?

To get a div’s offsetTop positions in React, we can get it from the ref assigned to the element.

For instance, we write

import { useRef } from "react";

function Component() {
  const inputRef = useRef();

  return (
    <>
      <input ref={inputRef} />
      <div
        onScroll={() => {
          const { offsetTop } = inputRef.current;
          //...
        }}
      >
        ...
      </div>
    </>
  );
}

to assign the inputRef to the input.

Then we get the offsetTop property from the inputRef.current property which has the input element.

Conclusion

To get a div’s offsetTop positions in React, we can get it from the ref assigned to the element.

Categories
React Answers

How to use Google Analytics with a React Next.js app?

Sometimes, we want to use Google Analytics with a React Next.js app.

In this article, we’ll look at how to use Google Analytics with a React Next.js app.

How to use Google Analytics with a React Next.js app?

To use Google Analytics with a React Next.js app, we can use the Script component.

For instance, we write

import Script from "next/script";
import Head from "next/head";

export default function Index() {
  return (
    <>
      <Head>
        <title>Next.js</title>
      </Head>
      <Script
        src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"
        strategy="afterInteractive"
      />
      <Script id="google-analytics" strategy="afterInteractive">
        {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){window.dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', 'GA_MEASUREMENT_ID');
        `}
      </Script>
    </>
  );
}

to add the Script component which has the Google Analytics code.

The Script component as a script tag in the head element.

Conclusion

To use Google Analytics with a React Next.js app, we can use the Script component.

Categories
React Answers

How to handle 401 error in Axios and React?

Sometimes, we want to handle 401 error in Axios and React.

In this article, we’ll look at how to handle 401 error in Axios and React.

How to handle 401 error in Axios and React?

To handle 401 error in Axios and React, we can add a response interceptor.

For instance, we write

axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response.status === 401) {
      // ...
    }
    return error;
  }
);

to call axios.interceptors.response.use with a function that runs when we get a response and a function that runs when we get an error respectively.

In the error handling function, we get the response status code with error.response.status.

If it’s 401, then we do some thing with the response.

Conclusion

To handle 401 error in Axios and React, we can add a response interceptor.