Categories
React Answers

How to fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React?

Sometimes, we want to fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React.

In this article, we’ll look at how to fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React.

How to fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React?

To fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React, we shouldn’t call state setter functions at the top level of the component.

For instance, instead of writing

const SignInContainer = ({ message, variant }) => {
  const [open, setSnackBarState] = useState(false);
  const handleClose = (reason) => {
    if (reason === "clickaway") {
      return;
    }
    setSnackBarState(false);
  };

  if (variant) {
    setSnackBarState(true);
  }
  return (
    <div>
      <SnackBar
        open={open}
        handleClose={handleClose}
        variant={variant}
        message={message}
      />
      <SignInForm />
    </div>
  );
};

We write

const SignInContainer = ({ message, variant }) => {
  const [open, setSnackBarState] = useState(variant ? true : false);
  const handleClose = (reason) => {
    if (reason === "clickaway") {
      return;
    }
    setSnackBarState(false);
  };

  return (
    <div>
      <SnackBar
        open={open}
        handleClose={handleClose}
        variant={variant}
        message={message}
      />
      <SignInForm />
    </div>
  );
};

We removed the

if (variant) {
  setSnackBarState(true);
}

from the SignInContainer component so that we won’t keep re-rendering the component as we change the open state, which causes an infinite loop.

Conclusion

To fix Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop error with React, we shouldn’t call state setter functions at the top level of the component.

Categories
React Answers

How to import a CSS file in a React Component?

Sometimes, we want to import a CSS file in a React Component.

In this article, we’ll look at how to import a CSS file in a React Component.

How to import a CSS file in a React Component?

To import a CSS file in a React Component, we just import it like any other module.

For instance, we write

import React from 'react';
import './App.css';

to import the App.css file into our app to load the styles in the CSS file.

Conclusion

To import a CSS file in a React Component, we just import it like any other module.

Categories
React Answers

How to make React component/div draggable?

Sometimes, we want to make React component/div draggable.

In this article, we’ll look at how to make React component/div draggable.

How to make React component/div draggable?

To make React component/div draggable, we can check if we pressed on the element with our mouse and set its position as the mouse moves if it is.

For instance, we write

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

const quickAndDirtyStyle = {
  width: "200px",
  height: "200px",
  background: "yellow",
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
};

const DraggableComponent = () => {
  const [pressed, setPressed] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const ref = useRef();

  useEffect(() => {
    if (ref.current) {
      ref.current.style.transform = `translate(${position.x}px, ${position.y}px)`;
    }
  }, [position]);

  const onMouseMove = (event) => {
    if (pressed) {
      setPosition({
        x: position.x + event.movementX,
        y: position.y + event.movementY,
      });
    }
  };

  return (
    <div
      ref={ref}
      style={quickAndDirtyStyle}
      onMouseMove={onMouseMove}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
    >
      <p>draggable</p>
    </div>
  );
};

export default DraggableComponent;

to check if the div is pressed with the onMouseDown and onMouseUp props.

If pressed is true, then we’re pressing on the div.

When the mouse is moving and pressed is true, then the setPosition function in onMouseMove is called.

In the useEffect callback, we watch the position value and set the transform style of the div as we drag the div.

The ref is set to the div with the ref prop.

Conclusion

To make React component/div draggable, we can check if we pressed on the element with our mouse and set its position as the mouse moves if it is.

Categories
React Answers

How to fix cannot update a component while rendering a different component warning with React?

Sometimes, we want to fix cannot update a component while rendering a different component warning with React.

In this article, we’ll look at how to fix cannot update a component while rendering a different component warning with React.

How to fix cannot update a component while rendering a different component warning with React?

To fix cannot update a component while rendering a different component warning with React, we should call functions from props inside the useEffect callback or in functions in the component.

For instance, we write

const HomePage = (props) => {
  useEffect(() => {
    props.setAuthenticated(true);
  }, []);

  const handleChange = (e) => {
    props.setSearchTerm(e.target.value.toLowerCase());
  };

  return (
    <div key={props.restInfo.storeId} className="container-fluid">
      <ProductList searchResults={props.searchResults} />
    </div>
  );
};

to call the props.setAuthenticated function inside the useEffect callback when the component mounts.

If we call it in the component at the top level, then the function runs on every render, which triggers the warning.

Conclusion

To fix cannot update a component while rendering a different component warning with React, we should call functions from props inside the useEffect callback or in functions in the component.

Categories
React Answers

How to fix window is not defined in Next.js React app?

Sometimes, we want to fix window is not defined in Next.js React app.

In this article, we’ll look at how to fix window is not defined in Next.js React app.

How to fix window is not defined in Next.js React app?

To fix window is not defined in Next.js React app, we check if window is undefined.

For instance, we write

if (typeof window !== "undefined") {
  // ...
}

to check if window isn’t undefined.

If it’s not, then we can run client side code safely by putting the code in the if block.

Conclusion

To fix window is not defined in Next.js React app, we check if window is undefined.