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

Unleashing the power of storytelling with React: A guide to creating dynamic story

weather.stories.ts export default { title: 'Widgets/Forecast', component: Weather, } const Template: Story<any> = (args) => <Weather {...args} />; export const Default = Template.bind({}); Default.args = { forecast: { ...

Bidirectional binding in Angular 2 Custom Directive

I've been working on a custom directive that automatically selects all options when the user chooses "All" from a dropdown. While I was able to get my custom directive to select all options, it doesn't update the model on the consuming component. ...

Adding space around images inside a DIV

Hey there! I recently did some work on my website, and now I'm facing a couple of issues. Check out the changes here! After tweaking a few things, the spacing around the images on the index page has gone wonky. I want the padding to be evenly distri ...

Is it possible to utilize rbac permissions independently of the authProvider system?

Currently, our team is utilizing react-admin and we are interested in implementing a permissions system for accessing resources. We have noticed that we can include permissions within the getPermissions function in the authProvider, but our current authent ...

Convert a JSON array into a new format

Here is the JSON data input provided: "rows": [ [ 1, "GESTORE_PRATICHE", 1, "GESTORE PRATICHE", "canViewFolderManagement" ], [ 2, "ADM ...

PNG file is not displayed on React TSX page despite absence of any errors

I've implemented this initial design template from GitHub (https://github.com/vikpe/react-webpack-typescript-starter). Additionally, I'm utilizing react-bootstrap and have a container that includes a backgroundImage. const heroImage = require(&q ...

Is it possible to link multiple references to a single Element/Node?

I am working on a function component that needs to pass the incoming ref from the parent to a div it is rendering. Additionally, I want to create and assign a separate ref inside the component to the same div. However, due to an element only accepting one ...

Assigning controller variables within an ajax request

I'm new to AngularJS and I have a question about controller attributes. I've created an attribute called 'anuncio', which contains an array of objects as shown below: var anuncioModule = angular.module('anuncioModule',[]); a ...

Maintaining the order of subscribers during asynchronous operations can be achieved by implementing proper synchronization

In my Angular setup, there is a component that tracks changes in its route parameters. Whenever the params change, it extracts the ID and triggers a function to fetch the corresponding record using a promise. Once the promise resolves, the component update ...

Struggling with creating and exporting TailwindCSS and NextJS

I'm encountering challenges in constructing and exporting my TailwindCSS and NextJS project. While everything works smoothly when running `npm run dev` with all Tailwind classes functioning properly, I face an issue when executing `npm run build && np ...

Is there a way to utilize JavaScript in order to trigger a CSS animation to occur at a designated time during a video

I have a cool animated image element that I want to play at a specific point in time during a video using JavaScript. I'm not sure how to make it happen, but I know the .currentTime property could be the key. My goal is for the animation to only play ...

Ways to set the minimum width of a div depending on its contents

As I work on my website, I encountered an issue with a div containing a table. The div expands to full width, but when I resize the screen, it shrinks causing the content to overlap. I am looking for a solution where the minimum width of the div adjusts b ...

Ensure that the entire webpage is optimized to display within the viewport

My goal is to make the entire website fit perfectly into the viewport without requiring any scrolling. The main pages I am focusing on are index, music, and contact, as the other two pages lead to external sources (you can find the link at the bottom of th ...

When using AngularJS, the templateUrl feature delays the initialization of the controller, causing issues with dependent code

Recently, I began experimenting with AngularJS and so far, everything seems to be going smoothly except for one small issue. Let's consider a scenario where I have two directives, with one directive relying on the other, like this: angular.module(&ap ...

Waiting for the listener script to finish its task in an Ajax call and then informing the user

I have developed a unique program that allows users to submit test cases from a specific webpage (main.php). The webpage triggers an ajax request to insert user data into MySQL using the file insert.php, with the value done=0. Subsequently, there is a list ...

Troublesome CSS Zoom causing issues with jQuery scrollTop

As I design a website that has a fixed width and zooms out on mobile browsers, I've opted to adjust the zoom using CSS rather than viewport meta tags: html, body { zoom: 0.8; } It's been effective so far, but now I'm facing an issue wi ...

Is it possible to filter JavaScript Array while ensuring that select options do not contain duplicate IDs?

I am utilizing two datatables with drag and drop functionality. Each row in the datatables contains IDs. When I drag a row from table 1 to table 2, the data is stored in an Array. I have an addArray function that pushes the IDs into the Array, filters out ...

What is the best way to center a div horizontally on all screen resolutions using only CSS?

The margin: 0 auto declaration is not having the desired effect for some reason. I have attempted using text-align in the header, as well as exploring various other options, but none seem to be working. This is my current code: div.middle { font-fami ...

Is it possible to make a fetch request from localhost:3000 to localhost:5000 in React, using the localhost identifier?

As I work on my react application hosted on localhost:3000, I encountered an issue while making a GET request in my code using fetch to localhost:5000/users. const [users, setUsers] = useState([]); useEffect(() => { fetch('http://localhost:5000/ ...