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:

https://i.sstatic.net/JHhpf.png

However, my current implementation looks like this:

https://i.sstatic.net/5N7hH.png

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

Retrieving a result from the reduce function in Angular

Is there a way to use the reduce function in order to return a list of objects? I am currently only able to return a single object with keys as project names and values as hours: { Name1: 9, Name2: 10, Name3: 30, } What changes can I make to my code to ac ...

Styling emails in an inbox with CSS

I am developing an email application and aiming for the inbox layout to be similar to that of Mac Mail. The emails are fetched from a database using ajax, outputting to XML. I then loop through the entries to extract the necessary elements. My concern li ...

React: Material-UI: How to justify two elements to opposite ends

Recently, I came across the following code snippet in reactjs using material ui theme: const useStyles = makeStyles((theme) => ({ root2: { maxWidth: 345, flexGrow: 1 }, paper2: { padding: theme.spacing(1), color: theme.palette.text ...

Testing API route handlers function in Next.js with Jest

Here is a health check function that I am working with: export default function handler(req, res) { res.status(200).json({ message: "Hello from Next.js!" }); } Alongside this function, there is a test in place: import handler from "./heal ...

Angular: Observing changes in the store and sending a message from a Service component to another component once the Service has finished specific tasks

Within our codebase, we introduce two classes known as GetDataAsyncService. This service is designed to wait for a change in the store before executing the block of code contained within it. By utilizing observables and subscribing to data changes with t ...

Avoid duplication of elements in Angular applications

Currently, I have a component that loads animated divs based on a datasource. *Note: In the example, I've used a lot of <any> because I haven't finalized the model yet. apiService.ts dataArray: Observable<Array<any>>; constru ...

The image displayed by the @vercel/og API route is not appearing correctly

I am currently facing an issue with my Next.js app hosted on Vercel Edge while trying to set up the Vercel/og package. You can find more information about it here: https://vercel.com/docs/concepts/functions/edge-functions/og-image-generation Upon loading ...

Center alignment is not being applied to the SVG element

I am currently working with React and when my component renders, it displays an SVG inside a div. Here is a snippet of the code: render() { return( <div class="myClass"> <svg> ... </svg> </div> ); ...

Develop a user interface designed specifically for a subset of JSX.Elements or ReactElement

For better organization, I decided to create an interface called IconInterface to group all my icons: import { IconProps, CaretProps, CheckboxProps } from "./IconProps"; interface IconInterface { (props: IconProps | CaretProps | CheckboxProp ...

Struggling with adding icons to the home screen in a Create React App?

When working with the manifest.json file, various icon sizes are specified as shown in this example: { “src”:”images/icons/apple-icon-57x57.png”, “type”: “image/png”, “sizes”: “57x57”, } In the index.html file, the ...

navigate to a different page upon submitting a form in React

I currently have this code snippet in my contact.js file: axios .post('http://localhost:3000/create', book) .then(() => console.log('Created')) .then(() => this.props.history.push({Home})) .catch(err => ...

Exploring Navigation in AngularJS with ui-router

I've encountered an issue with ui-router functionality in my code. Here's a breakdown of the problem: Within my index.html file <li> <a ui-sref="day2">Day 2</a> </li> <li><a ui-sref="day3">Day 3</a& ...

Navigating with React Router updates the URL but doesn't cause the component to render

I am encountering an issue with a React Material-UI component where I want to render another React component by changing the URL. The Create Jobs component is located in another file. Despite exploring various solutions on Stack Overflow, none of them hav ...

Is there a correlation between eliminating unnecessary imports and the size of the bundle as well as the speed of the build process

I am working on a Reactjs application built with Create React app, and I often encounter warnings during the startup and build process indicating that there are unused variables or imports in my Components. ./src/components/home/Header.js Line 10: & ...

Utilizing Node.js for Gmail API: Extracting Inline/Embedded Images

When working with email data, one approach is to use the gmail.users.messages.get() method. After fetching the email data, there are two functions used to handle the payload. function getBody(message) { var encodedBody = ''; try{ i ...

Please be aware that any fabricated comments will not be displayed in the posts object

-I have made an EDIT at the bottom of my original post -For my plunker, please visit this link Currently, I am learning AngularJS by following a tutorial located here. At this moment, I am stuck on the step called 'Faking comment data'. I have ...

Looking for help combining HTML5 Canvas and JavaScript to showcase images. Can anyone lend a hand?

I am currently in the process of developing an Android game using HTML5 and Javascript. I have managed to make some progress, but I have encountered a problem that has left me puzzled. Initially, my JS file and Html file were functioning well together for ...

The issue at hand involves Javascript, Ajax, latte, and Presenter where there seems to be a restriction on using GET requests for a file located

I have a query. I’ve been given the task of adding a new function to our web application. It was built on PHP by someone else, so it's proving quite challenging for me to debug as I am not familiar with this technology. I’m attempting to incorpor ...

Strategies for managing large numbers within WebGL GLSL shader programs

What is the best approach to handle large numbers like the one provided in GLSL? I have a shader that requires Date.now() as a uniform, which is defined as: The Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 ...

Unable to style table borders using CSS

I'm having trouble getting the borders to show up on my tables in my application. I added the "border: solid 2px black" line to my CSS, but nothing seems to be changing. Can anyone point out what I might be doing wrong? Here is my CSS: table { ma ...