Centering form fields in ReactJS using Material UI

I'm currently facing a challenge trying to center-align my react form.

Below is the structure of my form:

The technology I am using is Material UI for ReactJS

 <Grid item xs={12}>
          <Grid item xs={12}>

            <FormGroup noValidate autoComplete="on">
              <TextField
                label="SSN"
                type="number"
                className={classes.textField}
                name='ssn'
              />
            </FormGroup>

          </Grid>
      </Grid>

I have been attempting to align the form in the center.

If you need to view the entire component, this is the code snippet containing the form

import React from 'react';
import TextField from '@material-ui/core/TextField';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import Button from '@material-ui/core/Button';
import useStyles from '../src/styleMaker'
import { connect } from "react-redux";
import { FormGroup } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';


function App(props) {
  const useStyles = makeStyles(theme => ({
    container: {
      display: 'flex',
      flexWrap: 'wrap',
    },
    textField: {
      marginLeft: theme.spacing(1),
      marginRight: theme.spacing(1),
      width: 200,
    },
  }));
  const classes = useStyles();


  return (

    <React.Fragment>
    <div className={classes.container}>

        <Grid item xs={12}>
          <Grid item xs={12}>

            <FormGroup noValidate autoComplete="on">
              <TextField
                label="SSN"
                type="number"
                className={classes.textField}
                name='ssn'
              />
            </FormGroup>

          </Grid>
      </Grid>

    </div>

    </React.Fragment>

  );
}

export default App;

Could someone assist me in centering this form? I've spent the whole day trying with no success.

Answer №1

  1. To center a form horizontally, add the following style to your makeStyles:

    formGroup: {
      alignItems: 'center'
    }
    

    Then assign the class name formGroup to your <FormGroup>:

    <FormGroup className={classes.formGroup} noValidate autoComplete="on">
        <TextField
            label="SSN"
            type="number"
            className={classes.textField}
            name='ssn'
        />
    </FormGroup>
    

    Here is a demo of a centered form.

  2. If you want to center a form both vertically and horizontally, create a root <div> with absolute positioning and set its width and height to 100%. This will make the <div> take up the whole screen. Then use justify-content and align-items to center the form.

    container: {
      display: "flex",
      flexWrap: "wrap",
      position: "absolute",
      top: 0,
      left: 0,
      height: "100%",
      width: "100%",
      alignItems: "center"
    }, 
    

    Here is a demo of a form centered both horizontally and vertically.

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

Can you explain the distinction between onKeyUp and onKeyUpCapture in React (as well as onKeyDown/Capture)?

I was unable to find any existing documentation or questions related to my query, which surprised me. Upon inspecting the React index.d.ts file, I came across the following: // Keyboard Events onKeyDown?: KeyboardEventHandler<T>; onKeyDownCapture?: ...

Alert: Prop type validation error: The `component` prop provided to `ForwardRef(Link)` is invalid

We are facing an issue with our NextJS app where it works fine in production, and locally it renders correctly. However, we are encountering some unsightly warnings that we are trying to suppress. client.js:1 Warning: Failed prop type: Invalid prop `compon ...

What is the best way to arrange a GeoJSON features array based on a specific property value?

I need help sorting a GeoJSON file based on a property and then slicing it to keep only the top 5 features. For instance, I want to take this GeoJSON and arrange it in descending order by the incidents property: ... [ -75.1972382872565 ...

Tips for rendering a server-side component within a client-side component in a React 18 - Next.js 14 application router

As outlined in this RFC: Server Components or call server hooks/utilities cannot be imported by Client Components, as they are specific to server functionality. Currently, I am developing a project using react v18.2 and nextjs v14 with app router integr ...

Can you explain the variance in these code snippets when implementing React's setState() function?

Can you explain the variance between these two blocks of code? this.setState((state)=>({ posts: state.posts.filter(post=> post.id !==postRemoved.id) })) versus this.setState((state)=>{ posts: state.post ...

Is there a way to remove the scrollbar from the menu created with react-burger-menu?

How can I remove the scroll bar from the menu created with react-burger-menu? Despite trying various CSS properties adjustments, I have not been able to achieve the desired effect. Here is an image of the open menu and the corresponding CSS: (https://i.st ...

steps to create a personalized installation button for PWA

Looking to incorporate a customized install button for my progressive web app directly on the site. I've researched various articles and attempted their solutions, which involve using beforeinstallprompt. let deferredPrompt; window.addEventListener(& ...

What is the best way to stop setInterval on click using React Hooks?

Recently, I attempted to restructure my code using react hooks. However, I encountered some challenges as the setInterval and setTimeout functions did not behave as expected when I copied and pasted them into hooks. After multiple attempts, I was able to m ...

Issue: The module 'react-dev-utils/getPublicUrlOrPath' cannot be located

I recently deployed my React.js application on Heroku but encountered a message stating: The Browserslist indicates that caniuse-lite is outdated and advises to run the following command: npm update. In response, I executed npm update followed by ...

What could be causing me to receive [object Object] when making an axios GET request?

I am currently developing a react-express application and pulling data from a SQLite3 database. The data structure is as follows: [ { id:1, name: 'henry', photo: '/Photos/dog1.jpg' }, { id:1, ...

What is causing the difficulty in accessing the 'query' feature within the API, and why is the question bank failing to display?

Just wanted to mention that I am still learning about class based components, setState, and other concepts in async JS like axios. Below is a very basic example of what I can currently do. This is App.js: import Questions from './components/Ques ...

Every day, I challenge myself to build my skills in react by completing various tasks. Currently, I am facing a particular task that has me stumped. Is there anyone out there who could offer

Objective:- Input: Ask user to enter a number On change: Calculate the square of the number entered by the user Display each calculation as a list in the Document Object Model (DOM) in real-time If Backspace is pressed: Delete the last calculated resul ...

Applying a label to a TextField component using Material-UI

Is there a way to include a label within the TextField component? Material-UI, React, Performance ...

Exploring the possibilities of implementing the .map() function on a JSONArray within a ReactJS project using ES

When I receive a JSONArray from the server, my goal is to use .map() on it in order to extract key-value pairs of each object within the array. However, when I try to implement this code, I encounter an error stating "files.map is not a function". Can some ...

The parameter of the Card widget in Flutter is not properly defined

Need help with creating a reusable Card widget in my Dart app. Keep encountering a named parameter is not defined error. Any ideas on what could be causing this issue? Here's what I've attempted so far: Reinstalling the flutter SDK. No issues fo ...

Discovering the technique to unearth a specific value within an array nested within another array

I am encountering an issue with finding a value in one array inside another array and utilizing the resulting value to update the state using setState(). Here is the initial state: this.state = { initialStudents:[ {name:"str1",tags;["str","s ...

There was an error encountered: Uncaught TypeError - Unable to access the 'append' property of null in a Typescript script

I encountered the following error: Uncaught TypeError: Cannot read property 'append' of null in typescript export class UserForm { constructor(public parent: Element) {} template(): string { return ` <div> < ...

What is the method to select a singular value from an Autocomplete in Material UI?

I am currently working on an Autocomplete feature to add country calling codes in my project. However, I have encountered an issue where when selecting a code from the drop-down list, both the country name and its specific code are being displayed. My goal ...

What causes the updated value to be appended to an array when using the spread operator to modify an existing property's value?

In my state, I have an array of objects: const initialState=[{a:1},{b:2},{c:{d:3}}] const [state,setState]=useState(initialState) My goal is to modify the value of b to 5 within my event handler: function changeBToFive() { setState((state) => [ ...

What could be causing my state not to change in Nextjs even though I followed the quick start guide for Easy Peasy?

I recently encountered an issue while trying to implement easy peasy for global state management in my nextjs app. The problem I faced was that the state would only update when I changed pages, which seemed odd. To better understand what was going on, I de ...