What is the best way to align the 'Typography' component in the center?

Attempting to center it using flexbox with justify-content did not yield the desired result. I also tried replacing the Typography component with a div tag, but still no success.

import {AppBar,Zoom,Toolbar,Typography,CssBaseline,useScrollTrigger,Fab,makeStyles,IconButton,Container } from '@material-ui/core'
import PropTypes from 'prop-types';
import KeyboardArrowUpIcon from '@material-ui/icons/KeyboardArrowUp';
import styles from './menu.module.css'
import MenuIcon from '@material-ui/icons/Menu'


const useStyles = makeStyles(theme => ({
  root: {
    position: "fixed",
    bottom: theme.spacing(2),
    right: theme.spacing(2)
  }
}));

function ScrollTop(props) {
  const { children, window } = props;
  const classes = useStyles();
  // Note that you normally won't need to set the window ref as useScrollTrigger
  // will default to window.
  // This is only being set here because the demo is in an iframe.
  const trigger = useScrollTrigger({
    target: window ? window() : undefined,
    disableHysteresis: true,
    threshold: 100
  });

  const handleClick = event => {
    const anchor = (event.target.ownerDocument || document).querySelector(
      "#back-to-top-anchor"
    );

    if (anchor) {
      anchor.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  };

  return (
    <Zoom in={trigger}>
      <div onClick={handleClick} role="presentation" className={classes.root}>
        {children}
      </div>
    </Zoom>
  );
}

// ScrollTop.propTypes = {
//   children: PropTypes.element.isRequired,
//   /**
//    * Injected by the documentation to work in an iframe.
//    * You won't need it on your project.
//    */
//   window: PropTypes.func
// };

export default function BackToTop(props) {
  return (
    <React.Fragment>
      <CssBaseline />
      <AppBar>
        <Toolbar>
          <IconButton>
            <MenuIcon
              className={styles.icon}
              edge="end"
              color="inherit"
              aria-label="menu"
            />
          </IconButton>
          <Typography align='center' variant="h5">
            Información
          </Typography>
        </Toolbar>
      </AppBar>
      <Toolbar id="back-to-top-anchor" />
      <Container>
       <Typography></Typography>
      </Container>
      <ScrollTop {...props}>
        <Fab color="secondary" size="small" aria-label="scroll back to top">
          <KeyboardArrowUpIcon />
        </Fab>
      </ScrollTop>
    </React.Fragment>
  );
}}

Answer №1

One issue that may arise is the lack of centering for children within the Toolbar. To resolve this, you can implement the following:

const useStyles = makeStyles(theme => ({
    root: {
        position: "fixed",
        bottom: theme.spacing(2),
        right: theme.spacing(2)
    },
    toolBar: {
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
    }
}));

This styling can then be applied as follows:

<Toolbar className={classes.toolBar}>
    <IconButton>
        <MenuIcon
            className={styles.icon}
            edge="end"
            color="inherit"
            aria-label="menu"
        />
    </IconButton>
    <Typography align='center' variant="h5">
        Information
    </Typography>
</Toolbar>

Answer №2

If you want to ensure that the text is always centered, you can use the Container component to wrap it. Since the Container component automatically centers its children, the text will be centered as a result. Here's an example:

<Container>
  <Typography variant="h5">Information</Typography>
</Container>

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

Why does starting up the Firebase emulators trigger the execution of one of my functions as well?

Upon running firebase emulators:start --only functions,firestore, the output I receive is as follows: $ firebase emulators:start --only functions,firestore i emulators: Starting emulators: functions, firestore ⚠ functions: The following emulators are ...

Continuous Playback of Sound

Is there a way to autoplay an audio in loop without being blocked by browsers? Code : <audio id="audio1" src="assest/sound/1.mp3" autoplay="" /> <script> a = document.getElementById('audio1&apo ...

It seems like there is a glitch in the npm registry causing an undefined error. Let's try again

Attempting to add necessary dependencies to my project, however, encountering an error when executing yarn install [2/5] ...

The localhost successfully accessed req.session.userid, but unfortunately the virtual host cannot be reached at this time

Having some trouble here... I've spent days trying to figure it out but nothing seems to be working. I am using Node.js Express session on the backend with users. When I log in, I set req.session.userId = "userid" and have a middleware that ...

What is the best way to remove top divs without causing the bottom divs to shift upwards?

I am faced with a scenario where I must remove the topmost divs in a document without altering the user's view. Essentially, I need to transition from: ---------start of document div1 div2 div3 ---------start of window div4 div5 ------- ...

Searching is disrupted when the page is refreshed in NextJS

When I refresh the page, router.query.title disappears. I have read that I need to use getServerSideProps, but I'm unsure of what to include in the function. Can anyone provide guidance on how to resolve this issue? Update: I followed Yilmaz's s ...

Guide on incorporating ReactJS Material UI via a CDN using Webpack's external dependencies

Issue at Hand: I am facing a challenge in developing a website (web app) using React and Material UI. Everything works smoothly when utilizing npm. However, encountering an error with Material UI when attempting to link them as externals and import throug ...

The @Input() function is failing to display or fetch the latest value that was passed

I am currently working on an angular project, and I've encountered a situation where I'm attempting to send a value from a parent component to a child component using the @Input() decorator. Despite my efforts, the child component continues to di ...

What mechanism enables the scores on this sports ticker to refresh automatically without relying on ajax calls?

While browsing scores on , I found myself intrigued by the way they update their scores without using ajax calls or iframes. It's a mystery to me how this functionality is achieved. Can anyone shed some light on how it works? ...

Achieve a seamless redirection to the 404 component in Angular without altering the browser URL, while ensuring that the browsing

Whenever my backend sends a 404 error (indicating that the URL is valid, but the requested resource is not found, such as http://localhost:4200/post/title-not-exist), I need Angular to automatically redirect to my NotFoundComponent without altering the URL ...

The attempt to convert to ObjectId was not successful for the value located at the specified path "id" in the model

Encountered an Error: Cast to ObjectId failed for value "hist" at path "_id" for model "books" Greetings! ISSUE: Attempting to utilize other models within another model, specifically two models within one. The models in question are: models: { ...

Ways to address the alignment of list items within a drawer component using React

A couple of days back, I posted a query right here: How can I expand only one ListItem using a single method in React? I received an incomplete response which I accepted (although it seemed to work initially). Admittedly, my question may have been slight ...

The declaration file for module 'react-scroll-to-bottom' appears to be missing

I recently added react-scroll-to-bottom to my project and it is listed in my dependencies. However, I am encountering the following error: Could not find a declaration file for module 'react-scroll-to-bottom'. The path 'c:/Users/J/Desktop/w ...

A Sweet Alert to Deliver your Morning Toasty Message

I seem to be encountering an issue with my toast message. Instead of the toast popping up immediately after submitting the form, it keeps appearing even if I haven't submitted the form and even when navigating from another page to this one, the toast ...

Add various inputs to a table using JavaScript

I came across a situation where I needed to append lines into a table in a specific way. However, I encountered an issue with JavaScript not accepting any input type='text' for an unknown reason. When I used a normal text variable, it worked fine ...

Having trouble establishing a web socket connection using JavaScript

I'm experiencing an issue trying to connect my web socket to an Amazon instance using a specific IP address. I've had success connecting the web socket with a different IP and port using the Google Rest Client app, but now when I try to connect w ...

Updating a data table using POST values in ASP.NET: A step-by-step guide

I am working on updating values in my database and want to ensure that my script is functioning correctly. In order to check, I created a POST method to send the values and confirm they are being received. Now, my question is, once the values are being se ...

Combining AngularJS, D3, and JQuery on a single webpage can pose challenges, specifically with D3's ability to accurately read DOM dimensions

I am encountering an issue with my webpage not loading properly. I have structured it using a simple header-body-footer layout in html5 and CSS3. +----------+ | HEADER | +---+----------+---+ | BODY | +---+----------+---+ | FOOTE ...

Tips for shifting objects from a horizontal row to a designated vertical column when switching to a smaller display

I am currently utilizing bootstrap to enhance my website layout for mobile view. The main challenge I'm facing involves transitioning items from a row to a column in a specific order. In this case, I have two items in a row and I would like the first ...

Please rewrite the following sentence: "I am going to the store to buy some groceries."

As I navigate through my styled HTML page, an interesting sequence of events unfolds. When the Create New List button is clicked, a pink div emerges, contrasting with the orange hue of the All Lists div. At this moment, a new user has joined but hasn' ...