Ways to make the Select component in Material-UI lose its focus state once an item has been selected

Anticipated outcome:

Upon selecting an item, the Menu list will promptly close, and the Select component will no longer display a focus state. The borderBottom will change to 1px solid, and the backgroundColor will turn to white.

Current situation:

Select behavior after selecting an item

As depicted in the above image, the borderBottom appears as 2px solid, and the backgroundColor does not reflect white, indicating that the Select component remains in a focused state.

What steps should be taken to achieve the desired outcome?

Further Explanation:

In actuality, my concern lies with the visual appearance of the Select component's focus state rather than the focus itself. I am aiming for a behavior similar to that seen on fonts.google.com. Following the selection of a style (for example, Bold 700), the Select component maintains its focus state but without displaying any visible indications of being focused, which is precisely what I am seeking.

Answer №1

Here's an illustration demonstrating how you can personalize the focus appearance of Select.

If you're curious about customizing the underline, check out my response to a related question: How do I custom style the underline of Material-UI without using theme?

import React from "react";
...
export default withStyles(styles)(SimpleSelect);

https://codesandbox.io/s/material-demo-ttfwd?fontsize=14

Answer №2

One neat little trick you can employ is to make Select lose its focus deliberately:

<>
        <InputLabel
            id="CUSTOM_TITLE"
            shrink
        >
            {ANY_TITLE}
        </InputLabel>
        <Select
            ref={YOUR_SELECT_REF}
            input={<OutlinedInput notched label="ANY_TITLE" />}
            labelId="CUSTOM_TITLE"
            onClose={() => {
                ref.current.classList.remove('Mui-focused');
                ref.current.previousSibling?.classList.remove('Mui-focused');
            }}
            onOpen={() => {
                ref.current.classList?.add('Mui-focused');
                ref.current.previousSibling?.classList.add('Mui-focused');
            }}
        >
            {props.children}
        </Select>
</>

Answer №3

It's possible that I may have misunderstood the question, but one approach to solving this issue is by utilizing refs, as mentioned in the React documentation:

[...] Managing focus, text selection, or media playback.

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.selector= React.createRef();
    }
    render() {
        return <Selector ref={this.selector}>[...]</Selector>;
    }
}

You can then access the element itself by using this.selector.current, and you can set (or unset) its focus by calling this.selector.current.focus() or this.selector.current.blur() when the Selector's element is clicked. If you need to focus on another element upon clicking, you would obtain the ref for that specific element and handle it similarly.

I hope this solution aligns with what you were looking for!

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

Capture and handle JavaScript errors within iframes specified with the srcDoc attribute

My current project involves creating a React component that can render any HTML/JavaScript content within an iframe using the srcDoc attribute. The challenge I am facing is implementing an error handling system to display a message instead of the iframe ...

The issue with React Forward Ref not functioning properly has been identified specifically in conjunction with Custom Components

I am facing an issue where I cannot get the Material UI Tooltip to appear when wrapping my custom component. Despite using ForwardRefs correctly, the tooltip does not show up regardless of events like hover or click. const MyComp = ({ buttonRef }) => { ...

What is the procedure to switch the state using useState when an event is activated?

I'm trying to learn React by implementing a basic shop. One idea I had was to have multiple product images and when a user clicks on an image, it flips around to display additional information such as comments and ratings for the product. For this pr ...

Troubleshooting: My jQuery script for fading in content upon document ready is not

I'm currently working on a website where I want everything to fade in when the user enters the site. Take a look at my code: var celyLogin = $(".container"); $(document).ready(function () { /*! Fades in page on load */ $("container") ...

Guide for animating individual mapped elements in react-native?

After mapping an object array to create tag elements with details, I added an animation for the tags to zoom in on render. However, I wanted to take it further and animate each tag individually, sequentially one after the other. This appears to be a common ...

Transform React.js data from MySql into a variable

Hello there! I encountered an issue while working on coding my web app. **I am looking to execute this class only if the "swishes" value retrieved from a table in my MySQL database is greater than 0.** var thepos = 1; export default class W ...

A mock or spy must be used for the jest function

I'm having an issue with the last expectation not being called in a test I'm writing to test the actions within my application. const pushData = jest.fn(() => Promise.resolve()); test('anotherAsyncCall is fired to get more info', ( ...

What could be causing my webpack (react) build to fail when these modules are missing?

Starting a new project, I faced the challenge of installing webpack. Despite trying to ignore unnecessary modules in package.json, I encountered 19 errors during the build process that were related to modules not installed or needed. After researching solu ...

What is the best way to position a tooltip near an element for optimal visibility?

One div is located on the page as follows: <div id="tip"> Text for tip goes here... </div> And another one can be found below: <div class="element"> Text for element goes here... </div> There is also a piece of JavaScript ...

Customize the appearance of each TreeItem in JavaFX using CSS to assign unique

I am looking for a way to color individual Tree Items in a treeView based on specific conditions. I found a promising answer, but unfortunately, I am struggling to implement it. You can check out the answer here. My main obstacle is understanding how to u ...

Tips for incorporating data attributes into <figure> elements and retrieving them using CSS

Can we enhance a <figure> element by adding data attributes and then utilizing them in CSS? For example, I attempted figure { margin: 0 attr(data-margin %); } using <figure data-margin="15">...</figure> but it didn't yield the d ...

Adding map markers from a JSON feed to your React Google Map - a step-by-step guide!

I'm currently working on a React project that involves integrating Google Maps: const MarkerComponent = ({text}) => <div>{text}</div>; export default class NavMap extends Component { constructor(props) { super(props); this.s ...

Can you show me the method to import these ES6 exports? Are they specifically named exports or the default?

As I reviewed the code in the Material UI project, I came across a section that is exporting a variety of React Components: src/Dialog/index.js: export { default } from './Dialog'; export { default as DialogActions } from './DialogActions ...

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 ...

Is there a quicker alternative to the 500ms delay caused by utilizing Display:none?

My div is packed with content, including a chart from amCharts and multiple sliders from noUiSlider. It also features various AngularJS functionalities. To hide the page quickly, I use $('#container').addClass('hidden'), where the rule ...

Make the element switch from hidden to visible when hovering over it using CSS

I had a challenge to only show some rating text on my website when I hovered over it. Being new to coding with CSS and JavaScript, I was experimenting with overriding styles using the Stylebot extension in Chrome. I encountered an issue while trying to mo ...

What could be causing the whitespace around this element when using SASS from Refills / Bourbon.io?

I've recently started using the impressive SASS framework, Boubon.io created by the talented team at thoughtbot. As I experiment with their supplied templates (known as Refills), I'm finding that Bourbon.io serves as a versatile alternative to po ...

Using a combination of HTML and CSS3, craft this specific geometric design

Here's a sample image demonstrating how to create this button using CSS3. I would greatly appreciate any assistance! ...

Font rendering issue in Chrome extension

I have been diligently following various tutorials on incorporating a webfont into my Chrome extension, but unfortunately, none of them seem to be working for me. Despite all my efforts, the font remains unchanged and still appears as the default ugly font ...

Utilizing Next.js named imports without server-side rendering

I am looking to update this code snippet to use next.js dynamic imports without server-side rendering (SSR) import { widget } from "./charting_library/charting_library"; Here is what I have tried so far const widget = dynamic(() => import(&qu ...