Tips for aligning placeholder and text at the center in a React Material UI TextField

Existing Layout:

https://i.stack.imgur.com/Zv4Tg.png

Desired Layout:

https://i.stack.imgur.com/Xuj6O.png

The TextField element is displayed as follows:

<TextField
        multiline={false}
        autoFocus
        placeholder={props.defaultAmt}
        helperText="Enter amount to pay"
        margin="normal"
        InputProps={{
            startAdornment: <InputAdornment position="start">₹</InputAdornment>
        }}
        />

I am trying to horizontally center all content within the TextField. I attempted using textAlign: 'center' but it did not have any effect.

Answer №1

To customize the positionStart rule within the InputAdornment element, you can adjust the margin percentage based on your specific size and styling preferences for the Textfield. One possible approach is as follows (assuming that you are creating your styles using makeStyles, but feel free to modify it accordingly).

If you want to center the helperText, simply include a Typography component in the relevant prop since it requires a node type. Apply a style to the Typography component to align the text centrally:

const useStyles = makeStyles(() => ({
  centerAdornment: {
    marginLeft: "50%" // or adjust as needed
  },
  centerText: {
    textAlign: "center"            
  }
}));

Next, implement the customization:

<TextField
    multiline={false}
    autoFocus
    placeholder={props.defaultAmt}
    helperText={
                  <Typography 
                    variant="caption" 
                    className={classes.centerText}
                    display="block"
                  >
                      Enter amount to pay
                  </Typography>
               }
    margin="normal"
    InputProps={{
        startAdornment: (
            <InputAdornment 
                 position="start"
                 classes={{ positionStart: classes.centerAdornment}}
            >
                ₹
            </InputAdornment>
    }}
/>

Answer №2

To achieve this effect, adjust the alignment of the Child div and decrease the width of the TextBox. Create a style similar to the following:

const styles = {
   textBox: {
     "& $div": {
        justifyContent: "center",
       "& $input": {
          width: "30%"
        }
     },
   "& $p": {
      alignSelf: "center"
   }
}
};

Apply this style to the TextField element like so:

<TextField
   className={props.classes.textBox}
   multiline={false}
   autoFocus
   placeholder={"5000"}
   helperText="Enter amount to pay"
   margin="normal"
   InputProps={{
       startAdornment: <InputAdornment position="start">₹</InputAdornment>
      }}
  />

For a working example, check out this CodeSandbox link.

Answer №3

If you need assistance, just follow these simple steps:

<TextField
...
error={isError}
helperText={errorMessage}
FormHelperTextProps={{
  style: {
    textAlign: 'center'
  }
}}
/>

Answer №4

style={{ width: '600px', textAlign: 'center' }}

Include this property and test it out

Answer №5

Include inputProps in your Textfield component to center the text either for input or placeholder.

<Textfield
  ...
  inputProps={{ style: { textAlign: 'center' } }}
  ...
/>

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

Design a dynamic div element for banners that adjusts to different screen

Is there a way to create a responsive div similar to the img-responsive class in Bootstrap, but for a div element that changes its height relative to its width when the window size is adjusted? For example, if you look at the slider on this website "", yo ...

<JavaScript> changing the color of hyperlink in d3.js - <Organizational Chart>

screenshot The width of the link can be adjusted, but the color remains unchanged. I have attempted various solutions series.links.template.setAll({ strokeWidth: 2, strokeOpacity: 0.5, color: am5.color('#ffffff'), links: ...

Incorporate React JS seamlessly into your current webpage

As I delve into learning React and considering migrating existing applications to React, my goal is to incorporate a React component within an established page that already contains its own HTML and JavaScript - similar to how KnockoutJS's `applyBindi ...

Learn the ins and outs of Ember.js with our comprehensive tutorial and guide. Discover solutions to common issues such as DS

Learning Ember has been a challenging experience for me. The guide I am using seems to be lacking important information that I need. I keep encountering two specific errors: Uncaught Error: Ember.State has been moved into a plugin: https://github.com/e ...

What is the best way to generate a live map with constantly updating markers?

Is it possible for me to learn how to develop a live map similar to the one on this site: www.lightningmaps.org? It's fascinating to watch new markers pop up every few seconds. I'm interested in building a real-time map that can track IP locatio ...

Transfer the data-url attribute to the jQuery ajax URL

I am facing an issue with my form which includes a data-attribute holding a URL to an API JSON file: <form class="product" action="#" data-url="dist/scripts/main.js"> [...] </form> My goal is to transfer the URL from the data attribute to ...

Is it possible to pass a PHP array to JavaScript without using Ajax?

Currently, I have a JavaScript function that utilizes Ajax to fetch an array of data from PHP and dynamically populates a dropdown menu. Everything is functioning as expected. However, I am beginning to feel that using Ajax for this task might be a bit ex ...

Refreshing a NextJS Dynamic Route page causes the ID to disappear

I have been working on implementing dynamic routing to correctly display and retrieve information based on the id from the URL. Everything works fine when I initially visit the page, but upon reloading the page, the id becomes blank. Is there a solution fo ...

Exploring the differences between named exports/imports and imports with absolute path

Currently, I am working on developing a component library named awesome-components as an npm module. This library will include buttons, inputs, dropdowns, and other components that users can easily install in their react applications. However, I am facing ...

How to keep a div element fixed on the page's border vertically and horizontally adhered

Would you mind visiting the following link: and observing the layout of the page? My goal is to affix or "attach" a small div element to the right side of the page, just slightly outside of the right frame of the page. Vertically, I want this div to be ...

Express Validator is ineffective, consistently returning a value of 'undefined' with the message: 'Value is not valid'

I am facing an issue with using Express Validator to validate an async POST query on the server side in my PERN stack application. Despite setting up the validation checks, Express Validator seems to always return the same response regardless of the input ...

Creating a unique card component with React and custom Tailwind CSS styling

I am working on creating a project component using React: Despite my efforts, I have not been able to find the correct documentation for assistance. Additionally, I am facing challenges in utilizing next/image to ensure that it is the correct size. This ...

Modifying Checkbox BorderWidth in Material UI v5

Seeking assistance with adjusting the checkbox border width in Material UI v5. I currently have a custom checkbox and would like to remove the border width. Despite trying numerous solutions, I have been unsuccessful so far. checkbox <Checkbox de ...

Exploring the power of internal linking with GatsbyJS

I am currently developing a website using gatsbyjs. I have concerns about the crawlability of "onClick" for SEO purposes and I would appreciate some assistance. This is my current code: render={data => ( <div className='feed'> ...

Encountered an npm ERR while executing the React project

I'm encountering an issue with running my React project. When I use the command "npx start", I receive the following error message. Can someone please assist me with this? npm ERR! could not determine executable to run npm ERR! A detailed log of thi ...

Secret button concealed within a div, revealing only a helpful hint

On my website, there is a list of items where each item is represented by either a picture or a name enclosed in an <article> tag. Here is an example of how it looks: <article class="client-card"> <p><img width="211" height="106" ...

Creating dynamic web pages with jQuery is a simple and effective

I am currently using jQuery to create HTML elements with specific classes and then append them together. However, the code I have written is not adding the generated HTML to the container as expected. There are no errors being produced but the HTML is not ...

Incorporating @font-face webfonts into a Jekyll project

I'm currently working on incorporating webfonts into a Jekyll build. Interestingly enough, the fonts show up perfectly fine when I view them locally, but once I push my project to a live environment, the fonts mysteriously disappear. To make matters w ...

Obtain the name and current state of a checkbox in a React.js application

Upon clicking on a checkbox, I aim to retrieve the unique name (containing IDs from a GET API) and current value of the checkboxes (DefaultChecked containing values "true or false"). <td style={styles.gridrow}> {this.state.items.map ...

Dealing with Koa-router and handling POST requests

I am facing an issue handling POST requests in my koa-router. Despite using koa-bodyparser, I am unable to receive any data sent through my form. My template engine is Jade. router.js: var jade = require('jade'); var router = require('koa- ...