Steps to make the placeholder in an MUI TextField component move to the top of the box instead of staying within the border:

I'm working on styling a text field in MUI to achieve the look shown in the image below:

However, my current implementation looks like this:

Currently, when I click inside the text field, the placeholder slides up and is positioned within the border. But I want it to appear as shown in the first image where the placeholder is at the top left corner of the box.

I'm utilizing MUI's TextField component: https://mui.com/material-ui/react-text-field/

If anyone has any insights on how to achieve this, I'd greatly appreciate it!

Here is the code snippet:

CustomField.jsx

import React from "react"
import { styled } from "@mui/material/styles"
import TextField from "@mui/material/TextField"

const StyledTextField = styled(TextField)(({ width, marginTop }) => ({
  width: width || "343px",
  marginTop: marginTop || "25px",
  "& .MuiOutlinedInput-root": {
    "&:focus-within fieldset": {
      borderColor: "black",
      color: "black",
    },
  },
  "&:focus-within .MuiFormLabel-root": {
    color: "black",
  },
}))

const CustomTextField = ({ label, variant, helperText, value, onChange, disabled, width, marginTop }) => (
  <StyledTextField
    label={label}
    variant={variant}
    helperText={helperText}
    value={value}
    onChange={onChange}
    disabled={disabled}
    width={width}
    marginTop={marginTop}
  />
)

export default CustomTextField

App.jsx

const App = () => {
 const handleEmailChange = () => {};
 const email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f782849285b7929a969e9bd994989a">[email protected]</a>;

 return (
   <CustomTextField
        label="Phone number or email"
        variant="outlined"
        helperText="Some helper text."
        onChange={handleEmailChange}
        value={email}
      />
 )
}

Answer №1

It is recommended to utilize the variant="filled" option instead of variant="outlined".

To achieve the desired borders/outlines, you can either create a custom component or override the filled styles in the theme:

const FilledOutlinedInputField = styled((props) => (
  <TextField
    {...props}
    InputProps={{
      ...props.InputProps,
      disableUnderline: true,
    }}
    variant="filled" />
))(({ theme }) => ({
  '& .MuiFilledInput-root': {
    overflow: 'hidden',
    borderRadius: 4,
    backgroundColor: theme.palette.mode === 'light' ? '#FFF' : '#333',
    border: `2px solid ${ theme.palette.mode === 'light' ? '#F0F0F0' : '#000' }`,
    transition: theme.transitions.create([
      'border-color',
      'background-color',
      'box-shadow',
    ]),
    '&:hover': {
      borderColor: theme.palette.mode === 'light' ? '#08F' : '#FF0',
    },
    '&.Mui-focused': {
      backgroundColor: 'transparent',
      boxShadow: `${alpha(theme.palette.primary.main, 0.25)} 0 0 0 2px`,
      borderColor: theme.palette.primary.main,
    },
  },
}));

A live demonstration featuring the Reddit-style input field customization can be found in the documentation: https://mui.com/material-ui/react-text-field/#customization

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

The issue with adjusting the top position in jQuery

As I continued scrolling on my page, I encountered an issue with adjusting the top offset using jQuery on my element. I want the element with id goToLog to become fixed on the page after scrolling 80px. This functionality is working correctly. However, wh ...

When working on my asp.net webform, I incorporated an AgreementCheckBox along with a CustomValidator. However, I encountered an issue where the error message

Code for AgreementCheckBox: <asp:CheckBox ID="AgreementCheckBox" runat="server" ForeColor="Black" Text="Please agree to our terms and conditions!" /> Code for AgreementCustomValidator: <asp:CustomValidator ID="AgreementCustomValidator" runat=" ...

"Enhanced interactivity: Hover effects and selection states on an image map

Hello there, I need assistance with my code. Here it is: <img id="body_image" usemap="#body_map" src="assets/images/body.jpg" alt=""> <map name="body_map"> <area shape="poly" alt="d" href="#body_chart" name="ad" coords="153, 153, 145, 1 ...

Iterate over the table data and present it in the form of a Google

I'm struggling to extract data from a table and display it in a google chart. I need some guidance on how to properly loop through the information. HTML <tr> <th>Date</th> <th>Score</th> <th>Result< ...

using Javascript to eliminate necessary tags from concealed tabs

My goal is to dynamically remove the required tag from fields in hidden tabs when a tab is clicked using JavaScript. The presence of the required tag on unused fields causes issues with form submission, preventing data insertion into the database. Here&apo ...

Issue with window.location.href and unexpected behavior in Firefox 7

I can't seem to figure out the issue I'm encountering on FF7 My ajax calls are returning a json object (jquery). if(data.result=='ok') { var url = baseURL + "azioni/makeForm/" + data.actcode + "/DIA/" + data.az_id; console.log ...

What is the best way to pass JavaScript object literals from a Node.js server to the frontend browser?

In Node, I am working with JavaScript object literals containing methods in the backend. For example: const report = { id: 1, title: 'Quarterly Report for Department 12345', abstract: 'This report shows the results of the sales ...

Font Awesome symbols using the class "fa-brands" are not functioning as expected

I have included a font awesome library in the header using the following code: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> However, when I try to display an ic ...

Struggling with retrieving empty parameters, queries, and body from an Axios API call for the past three days. It's a learning experience as I am new to the MERN stack

There seems to be an issue where only empty JSON like {} is coming as output. I am looking for a way to access the parameters sent from the routes in this scenario. On the Frontend: let api = axios.create({ baseURL: "http://localhost:5000/validateSignI ...

Arrangement featuring two distinct types of tiles

Looking for a way to achieve this layout using just CSS or a combination of CSS and a little JS. Click on my avatar to see the reference image enlarged =) I've tried using floats and display options but haven't been successful. Take a look at htt ...

Are there any features in DataGrid MUI that allow for exporting columns containing renderCell functions with complex objects?

I am trying to export a table using DataGrid @mui/x-data-grid with the help of a CustomToolbar One of my columns is set up like this: { field: 'industry_type', headerName: 'Industry', renderC ...

Difficulty encountered in displaying HTML within a React component

Struggling to display HTML in my React code, whenever I click 'signup' after starting the page, it shows the 'login' view instead. Could there be an issue with how I'm linking everything together? App.js class App extends Compon ...

Mastering the use of expressions in ng-click and ng-show in AngularJS

I've been working on creating expandable rows within a table, but I'm encountering some issues. Despite not receiving any error messages, the functionality isn't behaving as expected. I suspect there might be an issue with how I'm using ...

What are some strategies for efficiently positioning buttons using CSS to prevent unwanted consequences?

Below is the CSS and HTML code, detailing a specific issue. * { box-sizing: border-box; font-family: Georgia, 'Times New Roman', Times, serif; } body { margin: 0; font-family: Georgia, 'Times New Roman', Times, serif; } .topn ...

Discovering similarities among array elements by looping through an array

Two sets of arrays have values obtained using the data-attribute(data-product-name). One set contains the full list of available items, while the other set consists of selected items associated with a country. <!-- the item list --> <div ...

Display a single submenu on mouseover using Javascript

Hello there, I have been working on creating a small menu using only Javascript, but I am facing an issue where the onmouseover event is displaying all submenus instead of just one. Below is the section of code that is supposed to change style.display to ...

A method to find the sum of the final n elements in an array by employing Arr.reduceRight

I have successfully calculated the sum of the last n elements in an array using a for loop. Is it possible to achieve the same result using Arr.reduceRight instead? x = [1,2,3,4,5]; y = 0 for(let i=x.length; i>x.length-3; i--) { console.log(x[i-1]); ...

Guide to implementing external CSS in Material-UI for efficient styling without relying on Javascript

As I embarked on creating an application with the ReactJS framework and utilizing the Material-UI library, I noticed that all styles are currently being defined within Javascript. However, my preference is to style components using CSS. What steps can be ...

VS Code is under the impression that closing tags are absent, even though all of them have been

My Code Editor is indicating 7 missing closing tags in this component, but they are all present. The lines that the editor is flagging with ** have error messages marked in italics beneath the relevant closing tag. I am seeking advice on how to identify ...

What is the method for identifying modules that rely on a specific module?

Is it possible to view all dependencies modules of a specific module, similar to this: npm-remote-ls <module-name> But how can we see the modules that depend on a particular module? Any help would be appreciated. Thank you. ...