having difficulty implementing the blur effect in reactJS

Currently, I am working on developing a login page for my project. Below is the code snippet I have implemented for the functionality:

import React, { useState, createRef } from "react";
import { Spinner } from "react-bootstrap";
import { ClipLoader } from "react-spinners";
import "./style.css";

function Login() {
  const [loading, setLoading] = useState(false);
  const [disabled, setDisabled] = useState(false);

  const makeBlurEffect = () => {
    setLoading(true);
    setDisabled(true);
  };

  return (
    <div class= {loading ? 'blur' : 'container'}>
      <div>
        <input type="text" placeholder="username" />
        <br></br><br></br><br></br>
        <input type="text" placeholder="password" />
        <br></br><br></br><br></br>
        <button onClick={makeBlurEffect} disabled={disabled}>
          login
        </button>
        <br></br><br></br><br></br>
      </div>
      {loading ? (
        <div id="loadingDiv" class="box stack-top" style={{ background: "white", border: "2px solid black" }}>
          <ClipLoader /> &nbsp; &nbsp;
          <span id="loadingDivText" style={{ fontWeight: "bold", fontSize: "30px" }}>
            Loading...
          </span>
        </div>
      ) : null}
    </div>
  );
}

export default Login;

//end

CSS Styling:

body{
    background: black;
}

.container{
    width: 200px;
    height: 200px;
    position: relative;
    margin-top: 200px;
    margin-left: 500px;
    justify-content: center;
    align-items: center;
}
.box{
    width: 100%;
    height: 100%;            
    position: absolute;
    left: 0;
    opacity: 0.8;

    display: flex;
    justify-content: center;
    align-items: center;
}
.stack-top{
    z-index: 9;
    margin: -20px -20px -20px -80px;
    width: 400px;
    height: 150px;
    opacity: 1;
}

.blur{
    width: 200px;
    height: 200px;
    position: relative;
    margin-top: 200px;
    margin-left: 500px;
    justify-content: center;
    align-items: center;
    filter: blur(2px);
  }

I am currently facing an issue where clicking on the login button triggers the blur effect for the entire screen instead of just the background. Any suggestions on how to solve this problem will be greatly appreciated.

Additionally, I attempted to use the opacity toggle approach but encountered an error message stating "unable to setProperty of null" when trying to apply it in the following way:

document.getElementById("loadingDiv").style.opacity = 1;

--------------edit

Modified login.js:

import React, { useState, createRef } from "react";
import { Spinner } from "react-bootstrap";
import { ClipLoader } from "react-spinners";
import "./style.css";

function Login() {
  const [loading, setLoading] = useState(false);
  const [disabled, setDisabled] = useState(false);

  const makeBlurEffect = () => {
    setLoading(true);
    setDisabled(true);
  };

  return (
    <div>

{loading ? (
          <div
            class="box stack-top"
            style={{ background: "white", border: "2px solid black" }}
          >
            <ClipLoader /> &nbsp; &nbsp;
            <span
              style={{ fontWeight: "bold", fontSize: "30px" }}
            >
              Loading...
            </span>
          </div>
        ) : null}


      <div class={loading ? "blur" : "container"}>
        <div>
          <input type="text" placeholder="username" />
          <br></br><br></br><br></br>
          <input type="text" placeholder="password" />
          <br></br><br></br><br></br>
          <button onClick={makeBlurEffect} disabled={disabled}>
            login
          </button>
          <br></br><br></br><br></br>
        </div>
      </div>


    </div>
  );
}

export default Login;

//end

Updated style.css:

body{
    background: black;
}

.container{
    width: 200px;
    height: 200px;
    position: relative;
    margin-top: 200px;
    margin-left: 500px;
    justify-content: center;
    align-items: center;
}
.box{
    width: 100%;
    height: 100%;            
    position: absolute;
    margin-left: 100px;
    justify-self: center;
    opacity: 0.8;

    display: flex;
    justify-content: center;
    align-items: center;
}
.stack-top{
    z-index: 9;
    margin: -20px -20px -20px -80px;
    width: 400px;
    height: 150px;
    opacity: 1;
}

.blur{
    width: 200px;
    height: 200px;
    position: relative;
    margin-top: 200px;
    margin-left: 500px;
    justify-content: center;
    align-items: center;
    filter: blur(2px);
  }

With the latest changes, the blur effect now works correctly, however, there is an alignment issue where the div does not appear centered. How can I address this alignment problem?

Answer №1

i was able to resolve the issue.

App.js

import logo from "./logo.svg";
import "./App.css";
import Login from "./login/login";
import React, { useState } from "react";
import Loader from "./loader/loader";

function App() {
  const [loading, setLoading] = useState(false);



  const [disabled, setDisabled] = useState(false);

  const makeBlur1 = () => {
    setLoading(true);

    setDisabled(true);
  };

  return (
    <div className="App">
      {!loading ? (
        <Login loading={loading} disabled={disabled} makeBlur1={makeBlur1} />
      ) : (
        <>
          <div style={{marginLeft: "480px"}}><Loader /></div>
          <Login loading={loading} disabled={disabled} makeBlur1={makeBlur1} />
        </>
      )}
    </div>
  );
}

export default App;

login.js

import React from "react";
import Loader from "../loader/loader";
import "./style.css";

function Login(props) {
  
  return (
    <div>

{/* {loading ? (
          <Loader />
        ) : null} */}


      <div class={props.loading ? "blur" : "container"}>
        <div>
          <input type="text" placeholder="username" />
          <br></br>
          <br></br>
          <br></br>
          <input type="text" placeholder="password" />
          <br></br>
          <br></br>
          <br></br>
          <button onClick={props.makeBlur1} disabled={props.disabled}>
            login
          </button>
          <br></br>
          <br></br>
          <br></br>
        </div>
      </div>


    </div>
  );
}

export default Login;

//end

style.css

//for login

body{
    background: black;
}

.container{
    width: 200px;
    height: 200px;
    position: relative;
    margin-top: 200px;
    margin-left: 500px;
    

  justify-content: center;
  align-items: center;
}
.box{
    width: 100%;
    height: 100%;            
    position: absolute;
    margin-left: 100px;
    justify-self: center;
    opacity: 0.8;  /* for demo purpose  */

    display: flex;
  justify-content: center;
  align-items: center;

}
.stack-top{
    z-index: 9;
    margin: -20px -20px -20px -80px; /* for demo purpose  */
    width: 400px;
    height: 150px;
    opacity: 1;
}

.blur{
    width: 200px;
    height: 200px;
    position: relative;
    margin-top: 200px;
    margin-left: 500px;
    

  justify-content: center;
  align-items: center;
    filter: blur(2px);
  }

loader.js

import React from "react";
import { ClipLoader } from "react-spinners";
import "./style.css";

function Loader() {
  return (
    <div
      class="box stack-top"
      style={{ background: "white", border: "2px solid black" }}
    >
      <ClipLoader /> &nbsp; &nbsp;
      <span style={{ fontWeight: "bold", fontSize: "30px" }}>Loading...</span>
    </div>
  );
}

export default Loader;

//end

style.css

//for loader

body{
    background: black;
}

.box{
    width: 100%;
    height: 100%;            
    position: absolute;
    margin-left: 100px;
    justify-self: center;
    opacity: 0.8;  /* for demo purpose  */

    display: flex;
  justify-content: center;
  align-items: center;

}
.stack-top{
    z-index: 9;
    margin: -20px -20px -20px -80px; /* for demo purpose  */
    width: 400px;
    height: 150px;
    opacity: 1;
}

when the login button is clicked, it will blur the background and display the loader div.

Answer №2

To save yourself time and effort, or if you're looking for a solution that's not too complex, you can check out this handy package:

react-spinner-overlay

All you need to do is insert the following code snippet into your App.js file:

      const [loading, setLoading] = useState(false);
    
      const dispatch = useDispatch();
    
      const logOut = async (evt) => {
        setLoading(true);
        evt.preventDefault();
        dispatch(logout(user.token))
          .then(() => {
            setLoading(false);
          })
          .catch(() => {
            setLoading(false);
          });
      };

  return (
 <RingSpinnerOverlay loading={loading}  overlayColor="rgba(0,153,255,0.2)" color="#0275d8" borderWidth = "4"
  />

      <div className="App">
...
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What method can I use to identify the most widely-used edition of a specific npm module?

While the npm registry does provide metrics on the most depended packages, have you ever wondered if it's possible to determine the most popular version of a specific package? For example, as a user considering upgrading to react-router^4.0.0, wouldn ...

Enhanced functionality in MUI TablePagination now allows users to easily select their desired page

I've implemented MUI TablePagination to enable pagination in my table. The code is performing well, offering most of the features I need: Users can choose between displaying 5, 10, or 20 entries per page using a dropdown. The number of pages displaye ...

Transferring data to a child component through Route parameters

Although I have come across numerous questions and answers related to my query, I still seem unable to implement the solutions correctly. Every time I try, I end up with an 'undefined' error in my props. Let's take a look at my parent compo ...

How to apply dynamic styling to a MatHeaderCell using NgStyle?

My goal is to dynamically style a MatHeaderCell instance using the following code: [ngStyle]="styleHeaderCell(c)" Check out my demo here. After examining, I noticed that: styleHeaderCell(c) It receives the column and returns an object, however ...

Exploring the application of the PUT method specific to a card ID in vue.js

A dashboard on my interface showcases various cards containing data retrieved from the backend API and stored in an array called notes[]. When I click on a specific card, a pop-up named updatecard should appear based on its id. However, I am facing issues ...

Tips for resolving the "ModuleNotFoundError" issue in Vercel when trying to deploy a Next.js application

Every time I attempt to deploy my website to Vercel, I am encountering this ModuleNotFoundError. Despite renaming my components and CSS modules, the error persists. If anyone has a solution to this issue, please share as I am clueless about what could be ...

Ways to expand media queries using sass

I have been using media queries to modify my code. @media (min-width: 576px) .modal-dialog { max-width: 500px; margin: 14% auto; } I want to change the media query, but after searching online, I couldn't find a suitable solution. I know the foll ...

Can you explain the step-by-step process of how an await/async program runs in TypeScript/JavaScript or Python?

As a C++ developer specializing in multithreading, I've been diving into the intricacies of async/await. It's been a challenge for me as these concepts differ from how C++ programs are typically executed. I grasp the concept of Promise objects, ...

Another option instead of using useCallback

Forgive me if this is a novice inquiry, but I am still learning JavaScript and React. I recently discovered the necessity of utilizing useCallback to wrap callback functions in order to prevent them from being recreated constantly when used within a fun ...

Vue 2.0: Exploring the Power of Directive Parameter Attributes

It has come to my attention that directive param attributes have been phased out in Vue.js 2.0. As a result, I am unable to use syntax like v-model="msg" number within an input tag. Are there alternative methods to achieve the same outcomes without relyi ...

Utilize the ng-click feature for swiping interactions in Ionic v1

I have a slide page on Ionic V1 that utilizes previous and next buttons. Here is an example: <button id="" class="button button-slide prev no-animation" ng-click="prev()" ng-show="activeIndex > 0" > BACK </button> While the click function ...

Navigating shadow dom elements in HTML with Selenium WebDriver

public WebElement retrieveShadowRootElement(WebElement element) { WebElement shadowRoot = (WebElement) ((JavascriptExecutor)driver) .executeScript("return arguments[0].shadowRoot", element); return shadowRoot; } WebElement rootElement= dri ...

While the Mongoose aggregate query is functioning properly in MongoDB, I am encountering difficulties in converting it to a Mongoose

Here is the JSON structure provided: [{ "_id" : ObjectId("626204345ae3d8ec53ef41ee"), "categoryName" : "Test Cate", "__v" : 0, "createdAt" : ISODate("2022-04-22T01:26:11.627Z"), "items" : [ { ...

Space within a series of photographs

Looking for some assistance: I am trying to maintain a consistent margin of 10px between posts and between photos in a photoset. However, when a post is a photoset, the margins of the bottom photo and the overall post add up to 20px. I want to retain the ...

The render of Javascript is not functioning properly in Chromedriver

For website testing in VisualStudio, I planned to use Selenium with Cromedrive. Unfortunately, I encountered difficulty in seeing items generated by Javascript on the page. It appears that chromedriver captures the pagesource before the JS has a chance to ...

Adding a Fictitious Pair to a JavaScript Object Literal

When I work with object literals in JavaScript, I often encounter syntax errors when adding a new label / value pair without including the trailing comma. This can be frustrating as it's easy to forget to include the necessary delimiter. .draggable({ ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

Customize Your Material UI Stepper with Unique Connector Colors for Each of the 4 Steps

Is it possible to use multiple connector colors with a different one at each step? For example, having the first connector be blue, the next green, then yellow, and finally red while maintaining the previous color. I've tried but all previous colors e ...

The JavaScript code is not functioning properly on the server after the ajax request

I have a situation where an ajax request is sending data to a PHP file, and then the PHP file is generating HTML content with some JavaScript code. The JavaScript code includes Google's chart library, but unfortunately the chart is not working as inte ...

Exploring the process of querying two tables simultaneously in MySQL using PHP

I currently have a search box in my PHP file that only searches from the "countries" table. However, I also have another table called "continent" and I would like the search box to retrieve results from both the "countries" and "continent" tables. Here is ...