Is there a way to adjust the selected color of a TextField?

I'm currently working with the Material-UI React library and I am trying to customize the border color of a TextField when it is clicked or in focus.

This is my attempt so far:

const useStyles = makeStyles((theme) => ({
  input: {
    borderWidth: '1px',
    fontWeight: 'bold',
    '& .MuiOutlinedInput-input:focused': {
      borderColor: 'green',
    }
  }
}));

However, despite my efforts, the borderColor remains blue. How can I resolve this issue?

Answer №1

How to Customize Focus Color in Material-UI v5

If you're looking to change the focus color of the TextField in Material-UI v5, you can do so by utilizing the color props. However, this method has its limitations as it only accepts predefined values. If you wish to use a custom color, you can implement the following code snippet:

'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning'

To set a specific color as the focus color, you can use the provided code snippet:

const CssTextField = styled(TextField, {
  shouldForwardProp: (props) => props !== "focusColor"
})((p) => ({
  // input label when focused
  "& label.Mui-focused": {
    color: p.focusColor
  },
  // focused color for input with variant='standard'
  "& .MuiInput-underline:after": {
    borderBottomColor: p.focusColor
  },
  // focused color for input with variant='filled'
  "& .MuiFilledInput-underline:after": {
    borderBottomColor: p.focusColor
  },
  // focused color for input with variant='outlined'
  "& .MuiOutlinedInput-root": {
    "&.Mui-focused fieldset": {
      borderColor: p.focusColor
    }
  }
}));

Implementation

<CssTextField focusColor='red' />

Demo

https://codesandbox.io/s/colortextfields-material-demo-forked-hpwc1?fontsize=14&hidenavigation=1&theme=dark&file=/demo.js

Customizing Input Styles in Material-UI v4

In Material-UI v4, you can modify the focused color border and label of the TextField using the following approach:

const focusedColor = "orange";
const useStyles = makeStyles({
  root: {
    // input label when focused
    "& label.Mui-focused": {
      color: focusedColor
    },
    // focused color for input with variant='standard'
    "& .MuiInput-underline:after": {
      borderBottomColor: focusedColor
    },
    // focused color for input with variant='filled'
    "& .MuiFilledInput-underline:after": {
      borderBottomColor: focusedColor
    },
    // focused color for input with variant='outlined'
    "& .MuiOutlinedInput-root": {
      "&.Mui-focused fieldset": {
        borderColor: focusedColor
      }
    }
  }
});
export default function CustomizedInputs() {
  const classes = useStyles();

  return (
    <div style={{ display: "flex", columnGap: 15 }}>
      <TextField className={classes.root} variant="outlined" />
      <TextField className={classes.root} variant="standard" />
      <TextField className={classes.root} variant="filled" />
    </div>
  );
}

Demo

https://codesandbox.io/s/67139471how-to-change-the-focused-color-of-a-react-material-ui-textfield-qlgpf?file=/demo.tsx

Answer №2

With the sx props of the Mui Textfield, you have the ability to modify the color of the outline when focused by using the following code:

const customStyle = {
  "& .MuiOutlinedInput-root": {
    "&.Mui-focused fieldset": {
      borderColor: "green"
    }
  }
}    

<TextField sx={customStyle} ...(other props)/>

To also change the color of the label when the field is focused, include this additional code in the style variable:

const updatedStyle = {
  "& label.Mui-focused": {
    color: "green"
  },
  "& .MuiOutlinedInput-root": {
    "&.Mui-focused fieldset": {
      borderColor: "green"
    }
  }
}

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

Position the colored div on the left side of the page

Here is the CSS I am currently using... <style type="text/css"> .widediv{width:1366px;margin-left:auto;margin-right:auto} </style> This CSS code helps me create my webpage : <body><div class="widedivv"> <!-- Content go ...

Introducing a new addition to the Material UI palette: an extra color to amplify your theme and integrate seamlessly into your design just like Primary and

One of the new custom colors I've added to the palette is blue: const rawTheme = createMuiTheme({ palette: { primary: { light: '#7ED321', main: '#417505', dark: '#2B5101', contrastText: &apo ...

Loading a Component in React (Next.JS) Once the Page is Fully Loaded

After implementing the react-owl-carousel package, I encountered an error upon refreshing the page stating that "window is not defined." This issue arises because the module attempts to access the window object before the page has fully loaded. I attempted ...

Searching for data in a bootstrap table that is not case-sensitive

Searching for and highlighting text within a bootstrap table has proven to be a challenge. Check out the Fiddle for an example: https://jsfiddle.net/99x50s2s/74/ HTML <table class='table table-bordered'> <thead> <tr& ...

CSS responsive grid - adding a horizontal separator between rows

I currently have a responsive layout featuring a grid of content blocks. For desktop view, each row consists of 4 blocks. When viewed on a tablet, each row displays 3 blocks. On mobile devices, each row showcases 2 blocks only. I am looking to add a ho ...

Replacing Material-UI with SCSS

In my current React project, I am utilizing MUI and Sass. The issue I am facing is that there are numerous scss files filled with !important declarations to override the MUI styles using Sass. To address this issue, I attempted to eliminate the !important ...

"Creating a HTML Table with Merged Cells using colspan and rowspan

Creating an HTML table with a unique layout is my latest project. I envision it to look like this: +-------+---+ | | | +-------+ + | | | +-----+-----+ | | | +-----+-----+ To achieve this, I'm utilizing a colgroup to split t ...

Leverage the theme.spacing method within the override property when customizing createMuiTheme

What is the best practice for utilizing theme spacing when configuring a theme using createMuiTheme? I have typically hardcoded these values in the past and haven't encountered any problems since my projects generally stick with the default theme spac ...

Generate individual CSS files using postcss and rollup

When I import each css file in my JavaScript, I want it to generate a new css file for the build. For example: import "./app.css"; import "./admin.css"; This would result in creating dist/app.css and dist/admin.css. My configuration fi ...

The error encountered with react createRef was caused by a faulty implementation

Here is the revised question post completing the answer In this particular code snippet, I have encountered an issue where my file browser opens correctly upon submission, however, the updated state is not reflected when I click the final submit button. ...

In ReactJS, unable to access the response object directly within the setState method

Having an issue updating the setSet as part of the output from my RestAPI. I keep getting an error stating that the response object is undefined. Strangely enough, I am able to log it outside of the setState method. Code addNewTodo = () => { axios.pos ...

I find it difficult to customize columns in grid template areas

I am having trouble adjusting the width of my header's columns to be 24vw, 24vw, 4vw, 24vw, and 24vw respectively. Despite specifying these widths, the browser is rendering all columns with equal width. Specifically, I am unable to change the width of ...

Tips for adding a background color in mui useStyle:

I can't seem to figure out why the background color isn't showing up in this code. Any help would be greatly appreciated, thank you! import { makeStyles } from '@mui/styles'; const useStyles = makeStyles((theme) => ({ root: { h ...

The provided property `verseObj.version_id` is not valid. It should be of type `object`, but a `string` value has been supplied

I am currently developing a unique and innovative public prayer journal that allows for the addition of verses in full stack. Surprisingly, I encountered an error when rendering the form which was not present a few days ago. Strangely enough, I have made n ...

Guide to personalizing React Material-UI Next components

I'm currently utilizing Material UI's next branch for my project and I want to customize the style of the TableHead component within the table. My approach was to create a new component called MyTableHead, wrap it around the TableHead component, ...

Tips for managing setTimeout() on a collection of elements

I have been attempting to utilize GPT for some time now but unfortunately, I haven't achieved satisfactory results. The Concept: I have implemented a snack bar feature to showcase errors. It takes an error message as input and stores it in a list. Th ...

Issue with Mui custom step not displaying on the screen

I'm having trouble with the MUI stepper component in my project. The steps are not rendering properly. The stepper is located within a dialog box: const DialogForm = ({ open, activeStep, children }: { open: boolean; activeStep: number; children ...

What is the best way to enable this image lightbox to function seamlessly with both horizontal and vertical images?

Looking to create a responsive image lightbox? After starting from an example on W3Schools (https://www.w3schools.com/howto/howto_js_lightbox.asp), I ran into issues with portrait oriented images. Ideally, the solution should handle both landscape (e.g., 1 ...

Ensure each alternate div has a unique background hue

While attempting to use CSS to assign a different background color to every second div element, I encountered an issue where both divs were affected when using (odd) and none when using (even). How can this be explained? .hoverDiv:nth-child(odd) { ba ...

Best practices for managing and coordinating the state of Next Js components

I am working on a feature that involves product cards with an "add to basket" button and a cart component that shows the number of products added. The added products are currently stored in local storage. My goal is to have the number in the cart compone ...