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. https://i.sstatic.net/GJBDh.png

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

What steps are involved in implementing an ordering system on a restaurant's website using React?

As I work on developing my portfolio using React, I'm interested in incorporating an online ordering feature. However, the information I have found through Google so far hasn't fully addressed my questions. Can anyone provide guidance on the best ...

Issue with background image positioning in IE 7 while scrolling

I am struggling with creating nested divs where the middle one has a fixed background image that remains static while the rest of the content scrolls. My solution works in Firefox, Chrome, and Opera but I'm encountering issues in IE7. Despite knowing ...

Using Styled Components to Implement Background Images in a React Application

I'm currently attempting to pass a background image using a prop, but I'm encountering an issue where it's indicating that url is undefined. const CardImage = styled.div` height: auto; width: 100%; background-size: c ...

Displaying a <div> element within a :before pseudoelement

Implementing the use of :before to insert an icon font into a div for a CSS3 hover state. I am looking to incorporate a div within the <a> tag in order for both elements to function as links: <a href="#set-4" class="column product hi-icon product ...

Invoking a Method in a React Component from its Parent Component

I am new to React and I have a question regarding how to call a method from a child component within the parent component. For example: var ChildClass = class Child { howDoICallThis () { console.log('Called!') } render () { retur ...

How can I customize the styling of Material-UI Popovers?

Is there a way to modify the default value of the max-height property for the Popover component? Even after trying to insert style={{'maxHeight': '365px'}}, I see no change: <Popover style={{'maxHeight': '365px&apo ...

The webpage hosted on Heroku displays a blank background, requiring users to refresh the page with an F5 key

I developed a group chat program using Python microframework flask, vanilla JavaScript, and Flask-SocketIO. The program is deployed on heroku and can be accessed here: . After deployment, I encountered the following issue: While the program worked fine o ...

Having trouble making swipe gestures work on react navigation's createMaterialTopTabNavigator?

Recently delving into the world of react-native, I'm faced with the challenge of creating a navigation tab that allows seamless switching between different routes either by tapping or swiping horizontally. I've opted to use createMaterialTopTabN ...

What are some ways to utilize tuples in TypeScript along with generics?

My mission is to create a type safe mapping object where I can define key/value pairs just once. I've managed to achieve this with the code below: const myPropTuple = [ [0, "cat"], [1, "dog"], [2, "bird"] ] a ...

Is there a way to eliminate the white border surrounding this input field? (JSFiddle link included)

http://jsfiddle.net/gn3LL/ .error { background-color: red; } <input id="firstname" class="custom error" name="first_name" type="text" placeholder="" class="input-xlarge"> I am trying to remove the small white border around the inside of the inpu ...

The property of undefined map cannot be read

import React from 'react'; import { Card, Text } from "react-native-paper"; import { SafeAreaView, } from "react-native"; class HackerNewsClone extends React.Component { constructor(props) { super(props); this.sta ...

Can you explain the use of parentheses in a typescript type when defining a key?

Could someone provide an instance of an object that matches the TypeScript type below? I'm a bit confused because I've only worked with interfaces before and have only seen square brackets. type Hash = { (data: Uint8Array): Uint8Array blockLe ...

The functionality of ngModel is not functioning properly on a modal page within Ionic version 6

Currently I am working on an Ionic/Angular application and I have encountered a situation where I am attempting to utilize ngModel. Essentially, I am trying to implement the following functionality within my app: <ion-list> <ion-item> <ion ...

CSS/HTML: Resolving Internet Explorer's Div Positioning Challenges

I've been struggling to find a resolution for this issue but I haven't been able to come up with anything effective. Here's the basic concept of what I'm trying to achieve. My goal is to have my layout divided into 3 divs. The first se ...

Getting the current page name within the app.component.ts file in Ionic 3 - a simple guide

Is it possible to retrieve the current active page name within the app.component.ts file in Ionic without having to add code to any other pages? ...

Performing multiple requests using Axios library in a React application

My goal is to make 2 requests and define variables using this.setState({}) for future modifications. This is the code snippet I have: class App extends React.Component { constructor() { super(); this.state = {user: false, repository :false} ...

What is the method to retrieve the data type of the initial element within an array?

Within my array, there are different types of items: const x = ['y', 2, true]; I am trying to determine the type of the first element (which is a string in this case because 'y' is a string). I experimented with 3 approaches: I rec ...

Having issues launching React project

As a newcomer to reactjs, I am currently exploring webpack configuration for my project. const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './main.js', output: ...

Linear gradient background issue not functioning properly when transitioning between screens using Next.js

Encountered an unusual issue with Next.js. My background linear gradients are not loading properly when navigating between pages. The link in question is: import Link from 'next/link' <Link href='/register'> <a> click m ...

Having trouble with the nth-child CSS property in Bootstrap?

My cards need some styling adjustments - specifically, I want the first and third card in each row to have a top margin of 50px. Strangely, this doesn't seem to work with Bootstrap, but it does with pure CSS. Is there a specific class in Bootstrap tha ...