Tips for customizing the focus border of a TextField input with the Material-UI theme

Struggling to customize the TextField border color and width in my own theme using Material-Ui v.5.4.0. After hours of research, I couldn't find a solution that works. It made me wonder if it's even possible to achieve this customization within the theme itself, which doesn't seem logical.

Here is my current theme code:

import { createTheme } from '@mui/material/styles'

// Colors
const blue = '#5A5BD4'
const blueDark = '#4f4fd8'

// Parameters
const buttonsBorderRadius = 20
const buttonPadding = '5px 15px'
const inputBorderRadius = 10

const theme = createTheme({
  components: {
    // Buttons
    MuiButton: {
      variants: [
        //   Blue button
        {
          props: { variant: 'blueButton' },
          style: {
            backgroundColor: blue,
            color: '#ffffff',
            borderRadius: buttonsBorderRadius,
            textTransform: 'none',
            padding: buttonPadding,
            '&:hover': {
              backgroundColor: blueDark
            }
          }
        },
        //   Transparent button
        {
          props: { variant: 'transparentButton' },
          style: {
            color: blue,
            borderRadius: buttonsBorderRadius,
            textTransform: 'none',
            padding: buttonPadding

          }
        }
      ]
    },
    // Inputs
    MuiOutlinedInput: {
      styleOverrides: {
        root: {
          borderRadius: inputBorderRadius,
          '& fieldset': {
            border: `1px solid ${blue}`
          }
        },
        focus: {
          border: `1px solid ${blueDark}`
        }
      }
    }
  }
})

export default theme

Snippet of my input code:

<TextField
                size='small'
                variant='outlined'
                label={t('paslelbimo_data_nuo')}
                type='date'
                InputLabelProps={{
                  shrink: true
                }}
                fullWidth
                value={publicationDateFrom}
                onChange={(e) => setPublicationDateFrom(e.target.value)}
              />

Answer №1

It seems like your question was a bit unclear regarding the desired effect when focused vs not focused. To provide some guidance, I have created a general example with exaggerated styling that you can adjust to suit your specific needs:

In this example, I am customizing the .MuiOutlinedInput-notchedOutline for both the focused and unfocused states:

const theme = createTheme({
  components: {
    // Inputs
    MuiOutlinedInput: {
      styleOverrides: {
        root: {
          ...
          "& .MuiOutlinedInput-notchedOutline": {
            border: `5px solid green`,
          },
          "&.Mui-focused": {
            "& .MuiOutlinedInput-notchedOutline": {
              border: `5px dotted red`,
            },
          }
        },
      }
    }
  }
});

For a live demonstration, you can check out the CodeSandbox example here: https://codesandbox.io/s/customstyles-material-demo-forked-uri26?file=/theme.js:84-531

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

Compressing CSS with the help of Gulp

Can anyone assist me with minifying my css in this gulpfile.js for compiling css? I have tried multiple code snippets from the internet but none of them seem to work. Your help would be greatly appreciated. Thank you. var gulp = require('gulp&apo ...

React app frequently retrieves images from the server whenever react-router is being utilized

I am currently working on a create-react-app project that utilizes the react-router-dom. Within this project, I have several Components that function as pages in a Single Page Application. Each page includes the following component: return ( <im ...

Pass Target Value Along with onClick Event in React

Is there a way to have one Display function that can control two Popper elements from Material UI independently? I attempted to assign different targets to each Popper element, but couldn't make it work using event.target.target. How can I achieve thi ...

Utilizing Promise chains within React for making REST API requests

I am currently working on a React application and I am relatively new to React, so I would appreciate some guidance in the right direction. My application involves building components that rely on making various Rest API calls to fetch the necessary data ...

The React DevTools display components with the message "Currently Loading."

I am currently facing an issue with debugging some props used in my React application. When I try to inspect certain components, they display as "Loading..." instead of showing the normal props list: https://i.sstatic.net/RtTJ9.png Despite this, I can con ...

Allowing horizontal scrolling in a table cell set to full width

I'm attempting to achieve the desired outcome by utilizing the code provided at What I'd like to know is why the scrolling function isn't working as expected. Instead of scrolling, it simply expands the table. To see the difference, try run ...

Trouble with setState function within constructor in ReactJS

Running the code below in React+Redux is proving to be a challenge as I keep encountering an unhandled exception 'NodeInvocationException: Cannot read property 'showText' of null TypeError: Cannot read property 'showText' of ...

Ensuring the container height remains consistent with fluctuating content dimensions

Imagine a container with content, where the container's width is fixed but its height adjusts based on its inner content. Initially, when the content causes the container to be a specific height, the challenge arises in shrinking the inner elements w ...

Assigning a style class to the material-menu component in Angular 2+ is not possible at this

Is there a way to apply a style class to mat-menu elements? I've tried various methods, but it seems like the styles are only visible when inspected using Chrome. HTML <mat-menu class="matMenuColor" #menu="matMenu"> <form #logoutForm ng ...

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

Adjusting the opacity of a div while scrolling

I've searched multiple pages, but haven't found a solution that works for me. I'm trying to make the text in my div gradually become more transparent as I scroll. Can anyone help with this? Here's my code: <script src = "/js/titleSc ...

Refresh React Native: Is there a way to trigger a re-render to refresh the userIngredients Value?

const [constructorHasRun, setConstructorHasRun] = useState(false); const [isLoading, setIsLoading] = useState(true); const [userIngredients, setUserIngredients] = useState([]); const [userRecipes, setUserRecipes] = useState([]); const user = useCo ...

Browsing through a collection of images Tinder-style, compatible across multiple platforms (Hybrid / HTML5 compatibility accepted)

I have a vision to develop an app similar to Tinder, where users can swipe through a stack of photos. I am wondering if anyone has knowledge of how to achieve this effect on multiple platforms. My current plan involves creating a web app using jQuery Mobil ...

What occurs when handling error responses while utilizing fetch with the next/revalidate option activated?

I am currently in the process of migrating a few API routes from the Page router to the newer App router in an application built with Next.js framework. Some of these routes involve requests to external APIs, one of which is known for its instability. Whi ...

An error occurred while trying to create a new instance using prisma.model.create. The argument `school_id` provided in data.subjects.create.2.school_id is not recognized for

My dilemma revolves around these two models: model School { id Int @id @default(autoincrement()) name String? center_no Int? type String? subjects SubjectPool[] } model SubjectPool { id Int @id @default(a ...

Learn the art of animating images in React Native for a stunning transformation

I am currently working on a mobile app that features a splashpage with an image displayed in the center of the screen. I have implemented an animated feature to move the image to the top of the screen, but unfortunately, it is not functioning as expected. ...

Incorporating a background-image to enhance the appearance of checkboxes

I am attempting to set up checkboxes that will display different images when checked and unchecked. Below are the checkboxes I am currently using: <input type="checkbox" name="fordCheckBox" value="Ford"> To assign background images to each checkbox ...

Show an image in the MUI datagrid when there are no rows present

In my project using MUI V.5 with React, I am looking to showcase an image within my grid when no results are found for a user's search query. However, I am unsure of how to access this particular section without rows (img reference) Click here for im ...

I am having trouble with properly utilizing the Audio.Sound feature in Expo. I am unable to pause or modify the playback status as needed

I encountered an issue when attempting to pause or update the status of the sound Object that was created using Audio.Sound(). An error message keeps popping up indicating that the sound is not loaded. Error: Cannot complete operation because sound is not ...

Increasing the height of nested Bootstrap columns by stretching them out

I am trying to ensure that the first two columns in both the green and violet rows always have the same height. I initially thought of using d-flex align-items-stretch, but it seems like it is not working because those elements are not within the same row ...