Customize the initial color of the text field in Material UI

I am currently working with the mui TextField component and facing an issue. I am able to change the color when it is focused using the theme, but I cannot find a way to adjust its color (label and border) in its initial state when it's not focused. It seems to always default to black, which makes it difficult to display properly against a black background.

Is there a way to set the initial color to white or any other preferred color? Thank you.

Additionally, I am encountering a similar problem with the Select list.

Below is the relevant part of my code:

class Register extends React.Component {
    render () {
        return (
            <Theme primary={{main: '#F5BD1F',dark: '#ffc100'}} secondary={{main : '#2a2a2a'}} >
            <Box sx={{backgroundColor: 'secondary.dark', display : 'flex', alignItems: 'center', justifyContent: 'center', minHeight : '100vh'}}>
                <Box sx={{minHeight : '50vh', width : '50vw'}}>
                    <div style={{margin : '50px'}}>
                        <h1 style={{textAlign : 'center', fontSize: '20px'}}>Register a Metahkg account</h1>
                        <TextField sx={{marginBottom: '20px', input : {color : 'white'}}} variant="standard" type="text" label="Username" required fullWidth /> 
                        <TextField sx={{marginBottom: '20px', input : {color : 'white'}}} variant="standard" type="email" label="Email" required fullWidth/>
                        <TextField sx={{marginBottom: '20px', input : {color : 'white'}}} variant="standard" type="password" label="Password" required fullWidth/>
                        <Sex/><br/>
                        <Button variant="outlined">Register</Button>
                     </div>
                </Box>
            </Box>
            </Theme>)}}

Custom Components:

Sex Component:

function Sex () {
    const [sex, setSex] = React.useState('');
    const changeHandler = 
    (e:any) => {setSex(e.target.value);}
    return (
        <FormControl sx={{ minWidth: 200 }}>
          <InputLabel>Sex</InputLabel>
          <Select value={sex} 
            label="Sex" onChange={changeHandler}>
            <MenuItem value={1}>Male</MenuItem>
            <MenuItem value={0}>Female</MenuItem>
          </Select>
        </FormControl>)}

Theme Configuration:

import { createTheme, ThemeProvider } from '@mui/material/styles'; 
declare module '@mui/material/styles' {
    interface Theme {
      status: {
        danger: string;
      };}
    interface ThemeOptions {
      status?: {
        danger?: string;
      };}}
export default function Theme(props:any) {
  const theme = createTheme({
    palette: {
      primary: props.primary,
      secondary: props.secondary
    }})
    return (
        <ThemeProvider theme={theme}>
            {props.children}
        </ThemeProvider>)}

Visit the website
View source code

Answer №1

Check out the code snippet and live example on CodeSandbox for a functional demonstration.

import { CssBaseline, MenuItem, Stack, TextField } from "@mui/material";
import { styled } from "@mui/material/styles";
import { Fragment } from "react";

const StyledTextField = styled(TextField)({
  "& label": {
    color: "black"
  },
  "&:hover label": {
    fontWeight: 600
  },
  "& label.Mui-focused": {
    color: "black"
  },
  "& .MuiInput-underline:after": {
    borderBottomColor: "black"
  },
  "& .MuiOutlinedInput-root": {
    "& fieldset": {
      borderColor: "black"
    },
    "&:hover fieldset": {
      borderColor: "black",
      borderWidth: 1
    },
    "&.Mui-focused fieldset": {
      borderColor: "black"
    }
  }
});

export default function HomePage() {
  return (
    <Fragment>
      <CssBaseline />
      <Stack
        spacing={2}
        margin={2}
        padding={2}
        height={"100vh"}
        component="form"
        backgroundColor="white"
      >
        <StyledTextField variant="outlined" label="Name" />
        <StyledTextField variant="outlined" label="Gender" select>
          <MenuItem value={1}>Male</MenuItem>
          <MenuItem value={0}>Female</MenuItem>
        </StyledTextField>
      </Stack>
    </Fragment>
  );
}

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

Tips for styling buttons in react-admin with custom CSS

I need some help with customizing buttons in react-admin. I am new to the platform and unsure about how to go about changing the button CSS for various actions such as create, edit, and export. Can anyone provide guidance on the best way to customize these ...

What's the best way to remove an item from a queue data structure in React state?

Currently in the process of building a unique project that allows users to pick between adopting dogs or cats. Users must input their name into the queue to adopt the dog that has been waiting the longest (both the human and animal queues are structured as ...

"Exploring the Functionality of Page Scrolling with

Utilizing Codeigniter / PHP along with this Bootstrap template. The template comes with a feature that allows for page scrolling on the homepage. I have a header.php template set up to display the main navigation across all pages. This is the code for th ...

Displaying Spinner and Component Simultaneously in React when State Changes with useEffect

Incorporating conditional rendering to display the spinner during the initial API call is crucial. Additionally, when the date changes in the dependency array of the useEffect, it triggers another API call. Question: If the data retrieval process is inco ...

Tips for storing an array consisting of 4 elements (objects) in local storage using React

Is there a way to replicate and add 4 objects with the same properties in an array, then store them in localStorage? I need to ensure that each object has identical properties. componentDidMount(){ const productData = Array(4).fill({ product ...

Issue in React-Redux Project: 'props' variable is not defined

I recently ran into an issue while working on my React-Redux application. Initially, I had defined the props before adding some content above the render() function. However, as soon as I added this new content, the app started encountering problems with re ...

Two vertical divs stacked on top of each other, each expanding to the entire height and width of the browser window

Is there a way to set the width and height of two divs on a webpage to match the dimensions of the browser window, requiring scrolling to view the second div? In addition, how can I ensure that the content within these divs is vertically centered? To ach ...

What are the implications of a project containing nested node_modules directories?

We are currently in the process of dividing our project into "sub modules" within a single repository. Our goal is to maintain aspects such as webpack configurations and express server globally, with a structure similar to the following: package.json serv ...

I am encountering an issue with the material ui dropdown component in my react native app where I am receiving a TypeError stating that it cannot read the property 'style' of undefined. This error is likely caused

Upon installation of Material UI and importing The Dropdown component, I encountered the error TypeError: Cannot read property 'style' of undefined, js engine: hermes. This is my code import React, { useEffect, useState } from "react"; import { ...

Expand the contents inside a div without affecting the actual div

Is there a way to zoom out the contents of a div similar to how a browser zooms out a page? I'm working on an application that loads a page into a div. However, I want to load the content without scroll bars. This would require zooming out the conten ...

Handling Promises in Angular 1 App using Typescript ES6/2015

Currently, I am working on an Angular 1.5 application that utilizes Typescript. My main concern is finding the most efficient way to handle ng.IPromise compared to Promise (ES6 promise). Personally, I would prefer to solely deal with the ES6 Promise type. ...

Display the chosen option in the console by using onChange() function; this is analogous to how onSelect()

I'm having trouble getting the value of a select element to log in the console. I managed to do this with an onSelect() method, but the onChange() method isn't returning anything. Here's what I tried with the onChange() method: <Form.Gr ...

"Uh-oh! Encountered a new unexpected runtime error. Can't seem

While working on my portfolio in Next.js, I encountered an issue. I added a header to display on all pages by placing it in _app.js without making any changes to _document.js. Here is the error message: Unhandled Runtime Error Error: No router instance fo ...

Error encountered when trying to update tree structure in TypeScript with new data due to incorrect array length validation

I have encountered an issue with my tree data structure in TypeScript. After running the updateInputArray(chatTree); function, I am getting an “invalid array length” error at the line totalArray.push(iteratorNode.data);. Furthermore, the browser freeze ...

Is there a way to modify or update the CSS classes and overall styling in .gsp files within the Grails framework?

What is the best way to dynamically update a DOM element's class and styling in response to specific conditions or events occurring in a .gsp file? ...

Enhance your AngularJS skills by incorporating multiple conditions into the ternary operations of ng-class

I am struggling to apply multiple classes when the condition in the ng-class attribute evaluates to true. Here is the code I have attempted so far, but it doesn't seem to be working: <div class="col-md-4" ng-mouseover="hoverButton=true" id="plai ...

Adjusting the Z-index of the autocomplete dropdown and exploring the functionality of getOptionSelected

I'm currently working on integrating the Autocomplete material ui widget into my web application, but I'm facing an issue where the drop-down menu appears behind my edit panel. While I can still use my arrow keys to navigate and select options, i ...

`Sending styles from a parent component to a child component: A step-by-step guide`

How can I pass a style object from a parent component to a child component? ParentComponent.js: const styles = theme => ({ field: { flexGrow: 1, position: 'relative', zIndex: 1, }, }); class ParentComponent extends React.Com ...

Indent the text within a span element that is displayed as an inline block

I am in search of a solution using only CSS for the following issue. Take into account the HTML below: <p> <span>Some text</span> <span>Some text</span> </p> Both <span> elements are set as inline-block. ...

SASS: incorporating loops within CSS properties

Is there a way to generate multiple values for a single property in CSS? background-image: radial-gradient(circle, $primary 10%, transparent 10%), radial-gradient(circle, $primary 10%, transparent 10%), radial-gradient(circle, $primary 10%, tr ...