Updating the outline of an OutlinedInput component using React's material-ui library

Just a heads up: this is a unique question, not a duplicate of How to change outline color of Material UI React input component?

I'm having trouble removing the outline on hover or focus with material-ui (React). I need this input to display a red border during warnings. I've tried adjusting the focused and hover styles as shown in the image below: https://i.sstatic.net/qbANE.png

This CSS is applied when the input is focused:

outlinedInputFocused: {
     borderStyle: 'none',
     borderColor: 'red',
     outlineWidth: 0,
     outline: 'none',
     backgroundColor: 'green'
  },

Component

 <OutlinedInput
            disableUnderline={true}
            notched={true}
            id="adornment-weight"
            classes={{root: classes.outlinedInput, focused: classes.outlinedInputFocused}}
            value={this.state.budgetValue}
            onChange={evt => this.updateBudgetValue(evt)}
            onKeyPress={evt => this.handleKeyPress(evt)}
            endAdornment={<InputAdornment sposition="end">BTC</InputAdornment>}
          />

Even though the CSS sets outlineWidth to 0 and outline to none, there is still an outline visible around the input. How can I modify or disable this outline?

Answer №1

To gain insight into how to override these styles, it is essential to examine their definitions in the Material-UI source code. The question you mentioned also provides a glimpse of the required syntax.

Displayed below is a condensed representation (styles unrelated to the outline have been omitted) of the styles extracted from OutlinedInput.js:

export const styles = theme => {
  const borderColor =
    theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';

  return {
    /* Styles applied to the root element. */
    root: {
      position: 'relative',
      '& $notchedOutline': {
        borderColor,
      },
      '&:hover:not($disabled):not($focused):not($error) $notchedOutline': {
        borderColor: theme.palette.text.primary,
        // Reset on touch devices, it doesn't add specificity
        '@media (hover: none)': {
          borderColor,
        },
      },
      '&$focused $notchedOutline': {
        borderColor: theme.palette.primary.main,
        borderWidth: 2,
      },
      '&$error $notchedOutline': {
        borderColor: theme.palette.error.main,
      },
      '&$disabled $notchedOutline': {
        borderColor: theme.palette.action.disabled,
      },
    },
    /* Styles applied to the root element if the component is focused. */
    focused: {},
    /* Styles applied to the root element if `disabled={true}`. */
    disabled: {},
    /* Styles applied to the root element if `error={true}`. */
    error: {},
    /* Styles applied to the `NotchedOutline` element. */
    notchedOutline: {}

  };
};

The "outline" of OutlinedInput can be managed by adjusting the border property on the NotchedOutline component enclosed within it. To affect this nested element, you must define a "notchedOutline" class (even if empty) for targeting the element based on different parent states (e.g., focused, hover).

Here is an example that completely eliminates the border:

import React from "react";
import ReactDOM from "react-dom";
import OutlinedInput from "@material-ui/core/OutlinedInput";
import InputAdornment from "@material-ui/core/InputAdornment";
import { withStyles } from "@material-ui/core/styles";

const styles = theme => ({
  root: {
    "& $notchedOutline": {
      borderWidth: 0
    },
    "&:hover $notchedOutline": {
      borderWidth: 0
    },
    "&$focused $notchedOutline": {
      borderWidth: 0
    }
  },
  focused: {},
  notchedOutline: {}
});
function App(props) {
  const { classes } = props;
  return (
    <div className="App">
      <OutlinedInput
        disableUnderline={true}
        notched={true}
        id="adornment-weight"
        classes={classes}
        value={1}
        endAdornment={<InputAdornment sposition="end">BTC</InputAdornment>}
      />
    </div>
  );
}
const StyledApp = withStyles(styles)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(<StyledApp />, rootElement);

https://codesandbox.io/s/94k34o11np

Answer №2

To implement custom styling directly within the component, you can utilize inline styles as shown below:

<MyCustomComponent style={{border: '2px solid black'}} />

Answer №4

OutlinedInput is crafted to always display its outline, requiring the use of TextField with variant set to 'outlined' by default and 'none' when focused. An illustration of Outlined Input Adornments can be found using TextField here

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

CSS Errors during Wordpress Transfer - Everything else is functioning properly

I am experiencing an unusual issue while trying to transfer my website to a new server with the same domain name but a different host. The website is not loading the layout or CSS properly, causing everything to display vertically instead of in its intende ...

The presence of multiple package.json files within a React Node.js project

I am new to working with react and I'm currently attempting to develop a project that incorporates react, node.js, and express. As I encountered numerous challenges when setting up the react environment on my own, I decided to opt for create-react-app ...

Increase or decrease value by 2 using useReducer instead of 1

I'm currently exploring the useReducer hook in react and encountering an issue. When I try to increase or decrease a unit by clicking the respective buttons, it subtracts 2 units instead of just 1. Any suggestions on how to fix this? Could it be that ...

jQuery show/hide functionality allows you to toggle the visibility of elements

I am looking to create a toggle button that expands the menu-wrapper width and hides the sidebar when clicked. Here is the initial CSS styling: #my-wrapper { Width:500px; } #sidebar-wrapper { width:200px; } Upon clicking the button, the CSS will update ...

Within a MERN application, when there is an app.get('/') route on the server and a <Route path='/' > component on the client side, which one will be executed first or given precedence?

If you have a React client with a nodejs express backend, the server is set up to serve Home.html when app.get('/') is hit. On the React side, you're using react-router-dom with this configuration: <Route path='/' component= ...

Building a Tailored WebSocket Feature within Redux Framework

As I delve deeper into this topic, it feels like falling down a rabbit hole. This Trading application is quite unique as it receives realtime data via web sockets based on a request-response paradigm. There are three separate SPA's where each user act ...

Mastering card sliding and spacing in React NativeLearn how to effortlessly slide cards horizontally in your React

My aim with the following code snippet is to achieve two objectives: Apply a margin of 20 units to each card Display all four cards in a single row, allowing users to swipe horizontally Unfortunately, I have not been successful in achieving either of th ...

``I am having trouble with my object key mapping when it is based on

https://i.sstatic.net/3uIeW.png I attempted the following code but it did not work as expected: Object.keys(singleproductdetails).map(function(detail, id) { return ( <div> <ul ...

The offspring elements are positioned outside of the main footer element

There seems to be an issue with my <footer>. All child elements of the <footer> are appearing outside of it. Does anyone know how I can properly place child elements inside the <footer> and align them from left to right? footer{ bac ...

Tips on saving an image in MongoDB

Is there a way to store an image in MongoDB with the following scenario? I have a product schema where I need to include another field for images. How can I manually upload and associate images with products using methods like Product.create or Product. ...

Adjusting the size of all elements on a webpage

Upon completing my project, I noticed that my localhost:3000 is zoomed in at 125%, causing it to appear less than ideal at 100% zoom. Is there a way to adjust the zoom/scale of my website to match how it appeared on my localhost environment? I came across ...

Discovering the secrets of Material-UI: uncovering the hidden depths of JSS-generated CSS class content, from static styles to dynamic classes

Using Material UI in my React project, I've come to understand that it utilizes JSS behind the scenes. According to the Material UI documentation for server-side rendering apps, we can extract the CSS string by using the following code: https://mater ...

Could someone please review my CSS code for the dropdown menu? I'm having trouble centering the navigation menu

As a newcomer to coding in CSS, I have tried the suggested solutions for my issue without success. Any help would be greatly appreciated. My goal is to center my menu on the page while keeping the container background covering the full width available... ...

Spacing for input placeholders on mobile safariIs there a gap for

UPDATE: Check out this minimum reproducible bug. Detailed instructions on how to run the code are in the readme file. Experiencing an issue with the bottom padding below an input placeholder specifically on mobile Safari. Below is a comparison of how the ...

Enhancing Your Website with Multiple Background Images in CSS3

Having trouble understanding how to position multiple background images with CSS3. I'm struggling to get them to display at the top, middle, and bottom of the page. Can you help me figure out how to make an image appear at different positions using a ...

Troubleshooting the Checkbox Oncheck Functionality

Before checking out the following code snippet, I have a requirement. Whenever a specific checkbox (identified by id cfc1) is clicked, it should not show as checked. I have implemented the onCheck function for this purpose, but I'm struggling to fig ...

Leveraging an API response to prompt a modal popup

I am trying to utilize the data returned from my API, which is a number within the range of -3 to +3, to trigger a modal display. After receiving the response from the API, I store the number in a state variable called setModalVisible. My expectation was t ...

The function finally is not available after executing the promises with api.get().thenReturn().catch()

I'm currently working on a React Native API call. On paper, everything seems to be in order - import DataAPI from "../../utils/API"; componentDidMount() { let merchantId = this.props.merchant.id; let api = new DataAPI(this.props.gath ...

Is the element with the "hidden" attribute and CSS display property set to "block" visible to the user agent

I have incorporated a helper element with specific CSS properties to assist my current structure, but I do not want it to be visible to anyone, including the user agent. Here is an example of the HTML: <button> <span>Real button text</s ...

How can we turn off the behavior of pie.htc specifically for versions of IE7 and lower?

I have implemented behavior(pie.htc) in my main css file for IE8, but I want it to not work for IE7 and lower versions. In my ie7.css file, I have the following style: #wrapper * {behavior:none} However, this does not disable all of the behavior set in m ...