Transitioning between modals using Tabler/Bootstrap components in a ReactJS environment

Currently, I am constructing a Tabler dashboard and incorporating some ReactJS components into it. Initially, I used traditional HTML pages along with Jinja2 templates. However, I have now started integrating ReactJS for certain components.

I prefer not to rely heavily on third-party tools such as react-tabler or bootstrap-tabler since they introduce unnecessary additional packages which may not be essential. Surprisingly, I have managed to develop an aesthetically pleasing Tabler dashboard using ReactJS components without the need for these extra packages.

The only issue I am encountering at the moment is related to displaying a Modal. Although the functionality itself works, the CSS transitions do not work smoothly initially. To address this, I implemented the following workaround:

// handle button click
const handleEditClick = (row) => {
    setIsModalOpen(true);
    modalRef.current.style.display = "block";

    // delay to ensure display:block setting first
    setTimeout(() => {
        modalRef.current.classList.add("show");
    }, 100);
};
    

I find this approach a bit makeshift and would like to explore alternative methods.

Displaying a Modal functions perfectly by setting the style="display:block attribute initially followed by adding the show class. This technique allows me to avoid excessive JavaScript coding. Nevertheless, the order of applying display:block is crucial. It seems that if this style is not established first, both changes occur simultaneously or perhaps the display:block attribute kicks in slightly later, resulting in a lack of transitional effect.

I experimented with including the event listener

modalRef.current.addEventListener("transitionend", handleTransitionEnd);
, but evidently, it works optimally with actual transitions rather than style alterations.

Is there a more elegant solution than relying on a 100ms timeout? Clearly, setting display:block as default is not viable as it renders my application unresponsive due to the opaque modal overlaying it.

Answer №1

I recently resolved this issue by incorporating two instances of useEffect. This approach was necessary to prevent the simultaneous addition of the "show" class alongside the display:block style.

In order to close the Modal, I utilized the transitionend event listener.

const MyComponent = () => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isButtonClicked, setIsButtonClicked] = useState(false);
    const modalRef = useRef(null);

    const [isStyleApplied, setIsStyleApplied] = useState(false);
    const [isClassApplied, setIsClassApplied] = useState(false);

    const handleEditClick = () => {
        setIsModalOpen(true);
        setIsButtonClicked(true);
    };

    useEffect(() => {
        const applyStyle = () => {
            if (modalRef.current && !isStyleApplied && isButtonClicked) {
                modalRef.current.style.display = 'block';
                setIsStyleApplied(true);
            }
        };

        applyStyle();
    }, [isButtonClicked, isStyleApplied]);

    useEffect(() => {
        const applyClass = () => {
            if (modalRef.current && isButtonClicked && isStyleApplied && !isClassApplied) {
                modalRef.current.classList.add('show');
                setIsClassApplied(true);
            }
        };

        applyClass();
    }, [isButtonClicked, isStyleApplied, isClassApplied]);


    const handleCloseModal = () => {
        setIsModalOpen(false);

        modalRef.current.addEventListener("transitionend", handleTransitionEnd);
        modalRef.current.classList.remove("show");

        function handleTransitionEnd() {
            modalRef.current.removeEventListener("transitionend", handleTransitionEnd);
            modalRef.current.style.display = "none";
        }
        setIsButtonClicked(false);
        setIsStyleApplied(false);
        setIsClassApplied(false);
    };

    return (
        <a className="dropdown-item" onClick={() => handleEditClick(row)} href="#">Open Modal</a>
        <EditModal row={selectedRow}  modalRef={modalRef} isOpen={isModalOpen} onClose={handleCloseModal} />
    );
}

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

Is it possible to protect passwords internally via URL and AJAX?

During my time at a previous company, we had an internal website that required a password to be entered at the end of the URL in order to view it. I suspect this was done using AJAX, but I am unsure. Even if AJAX was used, I do not know how to code it myse ...

Inquiring about the functionality of vertical and horizontal scrolling in jQuery localscroll

I recently finished building a webpage at . On this page, I have a set of main links along with corresponding sublinks. Currently, clicking on a main link causes the content to scroll vertically, while clicking on a sublink like Blue Inner Link 1 results i ...

The absence of modules is preventing the command from generating the Next app

I've been attempting to create a new Next.js app within my monorepo. Initially, I tried using the nx console extension in VS Code. While I was able to generate a new React app without any issues, I encountered an error when trying to create a new Nex ...

What is the best way to create a circular graph using SVG in React Native?

I am attempting to create a circular graph using SVG in React Native. My goal is to include a stroke in the chart. How can I achieve this? I have already accomplished this. https://i.stack.imgur.com/hPIst.png This is the desired outcome. https://i.s ...

jPlayer calculates the "duration" as 1,440 minutes on iOs devices for all mp3 files

My homemade webpage is designed for playing mp3s and viewing pdfs. I'm using jPlayer v 2.9.2 to play the mp3s, which works fine on PC but encounters issues on iPhone. The duration values are incorrect, showing "1439:59" remaining for all files, causin ...

Error in Angular 4: Undefined property 'replace' causing trouble

I've been trying to use the .replace() JavaScript function in Angular 4 to remove certain characters from a string. Here is the code snippet from my component: @Component({...}) export class SomeComponent implements OnInit { routerUrl: string = &apo ...

Type of Data for Material UI's Selection Component

In my code, I am utilizing Material UI's Select component, which functions as a drop-down menu. Here is an example of how I am using it: const [criteria, setCriteria] = useState(''); ... let ShowUsers = () => { console.log('Wor ...

Creating a Back Handler in a React Native Stack Navigator for seamless navigation

Is there a way in React Native Stack Navigator to navigate back to previous pages from some screens and disable the ability to go back from others? I've tried using Back Handler, but it doesn't seem to be working. How can I achieve this functiona ...

Issues with initializing React code - A beginner's guide to troubleshooting in React development

The div ID specified on line 9 is not being displayed as expected. The output does not include the text placed under the reactDom.render function. It only shows "Hello World from the index" on line 10. What could be causing this issue? I am utilizing t ...

Navigate to a different subdomain and place a cookie on the newly redirected subdomain

The version of Express is 4.x NodeJS is running on version 12.x At a.example.com, I have a listener for the GET method that redirects to b.example.com and sets a cookie on b.example.com. app.get('/foo', (req, res) => { res.cookie(' ...

The state is not being updated immediately when trying to set the state in this React component

Currently, I am working on a React component that is listening to the event keypress: import * as React from "react"; import { render } from "react-dom"; function App() { const [keys, setKeys] = React.useState<string[]>([]); ...

Hiding horizontal lines in a table without affecting vertical lines (Material-ui) - a step-by-step guide

Is there a way to hide the horizontal lines and timeslots in the table below without affecting the vertical lines? I attempted to use the visibility property on the td elements, but it hides both sets of lines. Any suggestions on how to resolve this is ...

The issue I'm facing with Angular 8 is that while the this.router.navigate() method successfully changes the URL

As someone who is relatively new to Angular, I am currently in the process of setting up the front end of a project using Angular 8. The ultimate goal is to utilize REST API's to display data. At this point, I have developed 2 custom components. Logi ...

Troubleshooting: Issues with executing a PHP script from jQuery

I found the source code on this website: It's an amazing resource, but I'm facing an issue where my JavaScript doesn't seem to be executing the PHP script... When I set a breakpoint in Chrome's debugger before the penultimate line (}) ...

Incorporate jQuery on elements that are dynamically loaded after the page has finished loading

I need to determine if a dynamically added button is enabled or disabled. How can this be achieved? My goal is to display a message when the button is disabled and remove it when the button becomes enabled. This is my current code: jQuery(document).read ...

Creating interactive button groups with responsive design in a Material UI and ReactJS web application

Is it possible to make ButtonGroup Buttons responsive? I heard about an attribute called "Orientation" in material-ui's ButtonGroup, but I'm not sure how to use it with media queries for changing orientation based on the device width. I'm st ...

Tips for handling the response after a view has been submitted on Slack using Bolt.js

Hey there! I added a simple shortcut to retrieve data from an input, but I'm facing an issue after submitting the view. The response payload is not received and the view doesn't update to give feedback to the user. Check out my code below: const ...

Innovative solution for detecting and replacing undefined object properties in Angular 2 with TypeScript

After encountering the issue of core.umd.js:3523 ORIGINAL EXCEPTION: Cannot read property 'fullName' of undefined I realized that the Exception stemmed from a Template trying to access a specific property: {{project.collaborators["0"]["fullN ...

Using Angular 4 to import an HTML file

I am trying to save test.svg in a component variable 'a' or svgicon.component.html. To achieve this, I have created the svgicon.component.ts file. However, it's not working. What steps should I take next? svgicon.component.ts import ...

Looking to trigger the closing of a q-popup-proxy by clicking a button from a separate component

I am currently working with a q-popup-proxy component in my project. <q-btn label="Add Fault" class="addFaultButton" dense @click="openPopUp()"> <q-popup-proxy position="center" v-if="openFaults" ...