The clock in NextJS/React shifts its position whenever it rerenders

I'm currently working on a clock widget in NextJS using SVG for scalability on large screens. The issue I'm facing is that the numbers on the clock aren't always the same width, causing the widget to shift slightly left or right every second. How can I fix this so that the widget stays centered?

Below is the code snippet:

// ** React Imports
import {ReactNode, useEffect, useState} from 'react'

// ** MUI Components
import { styled } from '@mui/material/styles'

// ** Layout Import
import BlankLayout from 'src/@core/layouts/BlankLayout'

// ** Library Import
import moment from 'moment'

interface PersonalizedClockProps {
  darkMode: boolean
  showSeconds: boolean
}

const PersonalizedClockStyled = styled('div')(({ theme }) => ({
  display: 'block',
  alignItems: 'center',
  justifyContent: 'center',
  height: '100vh',
  width: '100vw',
  overflow: 'hidden',
  '& svg': {
    width: '100%',
    height: '100%'
  },
  '& #time': {
    fontSize: '9rem',
    fontWeight: 500
  }
}))

const PersonalizedClock = (props: PersonalizedClockProps) => {
  const { darkMode, showSeconds } = props;
  const format = 'HH:mm:ss';
  const [time, setTime] = useState(moment().format(format));

  // update time every second
  useEffect(() => {
    const interval = setInterval(() => {
      setTime(moment().format(format));
    }, 1000);

    return () => clearInterval(interval);
  }, [format]);

  return (
    <PersonalizedClockStyled>
        <svg viewBox="0 0 560 300">
          <text id="time" x="50%" y="50%" className="classes.text" textAnchor="middle" dominantBaseline="central">
            {time}
          </text>
        </svg>
    </PersonalizedClockStyled>
  );
}

PersonalizedClock.getLayout = (page: ReactNode) => <BlankLayout>{page}</BlankLayout>

export default PersonalizedClock;

I have attempted changing the positioning to absolute and wrapping it in an outside div with absolute positioning but it did not resolve the issue.

Answer №1

If you're looking for a straightforward solution, why not consider using a fixed-width or monospace font? Browse through Google Fonts' Monospace category here

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

Troubleshooting Issue: Unable to Display Dropdown Menu with Bootstrap 5 and ReactJS

Attempting to showcase a simple NavBar from the bootstrap documentation (https://getbootstrap.com/docs/5.0/components/navbar/) in React. I installed Bootstrap using npm I bootstrap. Here is the structure of my App: https://i.sstatic.net/h41mr.png Below ...

Enable jquery offsetParent() function

$(document).ready(function(){ $("button").click(function(){ if ($("p").offsetParent().css("background-color") === "red") { $("p").offsetParent().css("background-color", "yellow"); } else { $("p").offsetParent().c ...

CSS Style for Highlighting Default Browser Border in Red

I'm currently exploring ways to design a red-bordered box that will appear when users fail to fill in required fields. Is there a method to ensure every browser displays the default red outline box for input requirements? For example: The code I&apo ...

What is the best way to address cookie issues while working on a full stack application that utilizes Vue and Express.js?

Developing a full stack application requires me to use Vue on port 5173 and Express on port 3000. One issue I face is the inability to store credentials in the frontend for backend communication during development. This challenge can be addressed by servin ...

Creating two submenus in the sidebar: a step-by-step guide

I am looking to implement a feature where clicking on the sidebar menu will reveal 2 submenus. Here is what I have implemented: $(document).ready(function () { $("[data-toggle]").click(function () { var toggle_el = $(this).data("toggle"); ...

Error message during Jest Enzyme testing: The "store" was not located within the scope of "Connect(App)"

I am faced with an issue in my index.js file, which includes: import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App' import * as serviceWorker from './servi ...

Error: The symbol $ is not recognized

This is a snippet of code that I've written to automate address filling and extract latitude/longitude/address information. <html> <head> <LINK rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" sr ...

Change the font weight to bold for the selected item in the Javascript menu, and

I am working on an ASP MVC application that includes a menu with JavaScript functionality to navigate between pages. Currently, when I click on a menu item, it becomes bold and remains bold even when another menu item is selected. This results in all menu ...

The Sentry captureException method is failing to display the full error object

I have successfully implemented Sentry in my NextJS application and am using `captureException` in the catch block to gather exceptions on the platform. However, I am facing an issue where it is only logging the error message and not all the nested error o ...

When sorting items, the page automatically jumps to the top of the screen

I have been working on creating a sortable portfolio using jQuery. One issue I am facing is that every time I click on a filter for the portfolio items, the page automatically scrolls to the top. Is there a way to prevent this from happening? You can vi ...

api for enhancing images in Laravel app through preview, enlarge, and zoom functionalities

As I work on my website, I aim to display images in a compact space, such as within a 300x300 <div>. What I envision is the ability for users to preview or enlarge these images upon clicking, allowing for a closer and more detailed view. For exampl ...

Load the div iframe when it is clicked

I'm looking for a way to optimize the loading of div elements on my website. Currently, when the page is loaded, all divs are also loaded but remain hidden until clicked. Is there a method to delay loading the content of a specific div until it's ...

Transfer a session ID cookie generated by express-session to a React front end on a different domain

I am currently developing a web application. The back end of my app is built using Node.js and Express.js, with a specific focus on utilizing the express-session module for implementing session-based authentication to maintain user logins. I understand tha ...

Creating an unconventional design utilizing ul and li elements with varied heights

Can I create the layout below using ul/li elements without any unusual tricks? All the elements in red should have the same width. Why do I want to use ul/li elements? Throughout the page, there are ul/li elements with a very similar layout, where all i ...

Toggle visibility of div elements in a list

Users have the option to either download a file by clicking on "download" or view it as a PNG in their browser by clicking "open". I found a solution on this platform for creating a show/hide toggle function. It worked well for one item, but I'm look ...

How can I align the selected option to the left in a CSS/jQuery selectbox?

I've been struggling to get the selected option aligned left like the other dropdown options. Even though I've added 'text-align:left;' in every CSS option, it's not working. I suspect that the JavaScript code is affecting the al ...

Perform different actions based on the state of a Vue JS checkbox: "Do This" when checked and

Attempting to create a checkbox that triggers one function when initially checked, and another when it is unchecked. I have tried the following approach. There is also a variable that has been read out and reflects the current status: <input type=" ...

How come my primary content is always spilling onto the header section?

Whenever I try to insert my header (after adding my context), it ends up getting placed below the context, making it invisible. I have attempted adjusting the padding and other sizes, but nothing seems to resolve the issue. https://jsfiddle.net/L30trdfn/ ...

Creating sitemaps for multi domain websites using NextJS

We are implementing a next-sitemap package to generate sitemaps for our Next.js pages located in the /pages directory. For pages that come from the CMS, we use server-sitemap.xml with SSR. Despite having 6 different domains, we manage them within a single ...

"Discrepancies Found: React app behaves differently between localhost and live

Lately, I've been working on updating my web portfolio and just launched it on my website. I noticed that the CSS is displaying differently on the live site compared to my localhost preview. The text appears smaller, colors are less vibrant, and the s ...