The Label in Material UI TextField is appearing on top of the border,

Incorporating Material UI TextField and Material UI Tab, I have encountered an issue. There are two tabs, each containing a text field. Upon clicking on the TextField, the label's border is supposed to open, but this behavior only occurs if the current Tab is set to Tab1!

To illustrate this problem, I recreated it in this CodeSandBox. The corresponding code is also provided below.

import React from "react";
import PropTypes from "prop-types";
import { makeStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";
import TextField from "@material-ui/core/TextField";

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <Typography
      component="div"
      role="tabpanel"
      hidden={value !== index}
      id={`scrollable-force-tabpanel-${index}`}
      aria-labelledby={`scrollable-force-tab-${index}`}
      {...other}
    >
      <Box p={1}>{children}</Box>
    </Typography>
  );
}

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired
};

function a11yProps(index) {
  return {
    id: `scrollable-force-tab-${index}`,
    "aria-controls": `scrollable-force-tabpanel-${index}`
  };
}

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    width: "100%",
    backgroundColor: theme.palette.background.paper,
    padding: 0,
    margin: 0
  },
  Tab: {
    MuiTab: {
      root: {
        minWidth: "130px"
      }
    }
  }
}));

export default function Demo(props) {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);

  function handleChange(event, newValue) {
    setValue(newValue);
    console.log(newValue);
  }

  return (
    <div className={classes.root}>
      <AppBar position="static" color="default">
        <Tabs
          key={"tabs"}
          value={value}
          onChange={handleChange}
          variant="scrollable"
          scrollButtons="on"
          indicatorColor="primary"
          textColor="primary"
          aria-label="scrollable force tabs example"
        >
          <Tab
            key={"tab1"}
            className={classes.Tab}
            label={0}
            {...a11yProps(0)}
          />
          <Tab
            key={"tab2"}
            className={classes.Tab}
            label={1}
            {...a11yProps(1)}
          />
        </Tabs>
      </AppBar>
      <TabPanel
        key={"panel1"}
        value={value}
        index={0}
        style={{ padding: 0, margin: 0 }}
      >
        <div key={"div1"}>
          hi im tab1{" "}
          <TextField
            key={"textfield1"}
            variant={"outlined"}
            margin={"dense"}
            label={"im tab 0 textfield"}
          />
        </div>
      </TabPanel>
      <TabPanel
        key={"panel2"}
        value={value}
        index={1}
        style={{ padding: 0, margin: 0 }}
      >
        <div key={"div2"}>
          hi im tab2
          <TextField
            key={"textfield2"}
            variant={"outlined"}
            margin={"dense"}
            label={"im tab 1 textfield"}
          />
        </div>
      </TabPanel>
    </div>
  );
}

Edit1:

A similar question was found...,
Material-UI TextField Outline Label is overlapping with border when conditionally rendered
It appears that this issue is not specific to tabs but rather influenced by conditional rendering, which became apparent while working with tabs

Edit2:
Despite assigning a key to the Textfield, the problem persists with an overlap between the Textfield border and label. The sandbox has been updated to reflect this change

Answer №1

Encountered an issue with overlapping text in a select element. After numerous attempts, I couldn't find a solution to the following problems:

  1. Label text overlapping with the border when focus is received
  2. Placeholder text touching the left border
  3. If not issue #1 - Placeholder text staying inside the borders even after selection/entry

https://i.sstatic.net/8Uw4L.png

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

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

Resolved these issues with the following steps that worked for me:

  1. <FormControl variant="outlined">

Ensure variant is added.

  1. <InputLabel id="input_designationselected" style={{backgroundColor:'white'}}>Designation*</InputLabel>

Set background for the label or refer to this link here

  1. Ensure the attribute labelId for the input control/select control matches the ID of the InputLabel

Achieved the desired output.

https://i.sstatic.net/1h5h8.png

It was frustrating for days - decided to share for others' benefit. Apologies if this is not the appropriate place to post.

Answer №2

When the label width is determined during the initial rendering of the TextField, it will only be recalculated if the label changes. The label's width is set to 0 when the TextField is initially rendered on your second tab and is not visible, resulting in no space allocated for it in the outline when switching the TabPanel to visible.

To resolve this issue, follow the same approach used in the demos within your TabPanel, which involves rendering the children of the panel only when it is visible so that the label width can be accurately calculated after the initial rendering.

Instead of using

<Box p={1}>{children}</Box>

you should use

{value === index && <Box p={1}>{children}</Box>}

https://codesandbox.io/s/textfieldontabs-0uwtl?fontsize=14&hidenavigation=1&theme=dark

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

Choosing and adding a div to another using the select method

Can someone assist me with this task? My goal is to dynamically append a div when selecting an option from a dropdown, and hide the div when the same option is selected again. Additionally, I want the name of the selected option to be displayed on the left ...

What is the best way to implement multiple onSubmit functions in react-final-form?

In my current form, there are two options for handling the data. I recall in redux-form that it was feasible to pass a function to `handleSubmit` like this: `handleSubmit(customOnSubmit)`. What is the equivalent approach in react-final-form? ...

MUI - React Custom Input fails to update upon value assignment

Utilizing React Hook Forms along with MUI React, the custom input wrapper I am using appears as follows: const CustomInput: React.FC<IInputProps> = (props) => { const { label, readonly, name, placeholder, hint, control, ...

Ensure that the URL is updated correctly as the client navigates between pages within a Single Page Application

Seeking a solution for maintaining the URL in a Single Page application as the client navigates between pages, with the URL changing in the background. I attempted using @routeProvider but it doesn't seem to be suitable for my situation. Any suggestio ...

A guide on utilizing portals in Next.js to move a child element beyond its direct parent container

Current Setup Wrapper export const ContainerComponent = () => { return (<ChildComponent/>); } Child Component export const ChildComponent = () => { return ReactDOM.createPortal( <aside> <div>{"I am a c ...

The custom hook you are attempting to use has resulted in an invalid hook

I'm struggling to identify the root cause of the invalid hook call error even though my hook is clearly placed within a functional component. I could use some help pinpointing the issue as I've tried several methods to resolve this error. Here i ...

How to Use Framer Motion in Next.js for window.innerWidth Less Than 768

I am trying to use window.innerWidth to control the timing of an animation (Framer Motion) in my Next.js project, but I keep encountering the error message: ReferenceError: window is not defined Here's a simplified version of my ValuesSection.jsx co ...

Avoiding redundant data in CRUD applications

In a CRUD application (back-end using express and front-end using react-redux), form values are submitted to a mongodb database with the following schema: import mongoose from 'mongoose'; var Schema = mongoose.Schema({ createdAt:{ type: D ...

The utilization of the Open Sans font family results in certain alterations to the user

Currently, I am working on developing a button widget using react. I have utilized the 'Open Sans' font family for the HTML body in order to maintain consistent UI styling. However, some of the styling elements break down when the 'Open Sans ...

React fails to acknowledge union types

I have the following types defined: export enum LayersItemOptionsEnum { OPERATOR, HEADER, } type sharedTypes = { children: string | ReactElement; }; type LayersItemStatic = sharedTypes & { label: string; option: LayersItemOptionsEnum; }; t ...

An unusual token occurred during the webpack compilation error in the Cypress test runner

I encountered an unexpected error during Webpack compilation while attempting to import a component into my cypress test spec Currently, I am using React version 17.0.0 and React-dom v17.0.0 What could possibly be the reason behind this issue? Take a lo ...

Is there a reason the hr tag elements aren't extending to the full width within the list?

I am having trouble with my hr tag elements in the table I created - they are not spanning the full width like the line above them. I have tried adjusting the width property but it doesn't seem to be working. Can anyone offer advice or guidance on how ...

Divs that overlap and share the same font may exhibit variations in letter spacing

In my design, I have a div that overlays another div with the exact same offsets and font properties. The upper div has a transparent background and typically covers the text of the underlying div. However, I recently noticed an issue with my script where ...

Tips for accessing the MuiChip borderRadius within material-ui

Looking to decrease the border radius on a chip component - any suggestions on how to target it correctly? I attempted targeting the root class, here is my sandbox where I'm experimenting with this: https://codesandbox.io/s/material-demo-forked-2osd6 ...

The Super Sub menu is failing to display correctly as intended

I encountered an issue while trying to create a Super sub-menu. The problem is that the super sub-menu appears when I hover over the main menus, instead of the sub-menus. I suspect there may be something wrong with the display: none; attribute, but I' ...

Issue arised while trying to open Bootstrap modal window due to conflict with surrounding elements

I'm facing a challenge with getting the bootstrap modal window to pop up on my website. Despite trying various solutions and troubleshooting steps, I haven't been able to resolve the issue. Even after eliminating all scripts except for the boots ...

Why is React not functioning properly in the browser? How can I fix this issue?

An error occurred: Unable to locate module '/Users/thomasmckenna/Downloads/React-Firebase-lesson-58/magic-memory/node_modules/fast-glob/out/index.js'. Make sure that the package.json file has a valid "main" entry at tryPackage (node:internal/modu ...

Positioning the close button on the top right edge of a Material-UI Dialog: A step-by-step guide

https://i.sstatic.net/ARTtq.png How can I include a close icon in the top right corner of the header section? I'm using the Material UI Dialog and everything works well, but I need a close button in the top section. Can anyone assist me with this? ...

Having trouble refreshing the page after making changes to the redux state

On the '/dashboard/gdrive' page, I am able to retrieve a list of Google Drive files. There is also an option to upload a new file. However, after uploading, while the Redux state confirms that the new file has been stored in the state, I encounte ...

Having trouble getting routing to function properly with react-router-dom

I'm currently assisting a friend with completing a React Project. I'm facing an issue while trying to set up routing using react-router-dom. The components inside the <switch> tag are not functioning properly. Below are snippets of my code: ...