Ways to adjust the border color when error helper text is displayed on a TextField

I am currently working with React Material UI's TextField element. What I aim to achieve is when the submit button is pressed, the helpertext displayed should be "Please enter the password."

It should look like this:

However, once the helpertext is shown, I want to change the border color of the TextField to a specific color defined in my SCSS file. This way, I can control the border color through the SCSS settings.

Essentially, what I need is for the TextField to have a red border and a blue outline when focused:

This is the code I have implemented so far:

<TextField
  id="form-el-2 outlined-basic"
  name="userName"
  variant="outlined"
  placeholder={"Please enter valid password"}
  helperText={
    errorMsgs.userNameErr && errorMsgs.userNameErr.length
      ? errorMsgs.userNameErr
      : null
  }
  onChange={handleChange}
  value={cabinetInfo.userName}
/>;

Along with the SCSS styling:

.MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline {
    border: 1px solid;
    border-color: #c4c4c4;
    outline: 1px solid $primary-color !important;
    outline-offset: 1px;
  }

Is it possible to achieve this effect? How can I implement this into my project? Any assistance would be greatly appreciated. Thank you in advance.

Answer №1

To give your component a custom appearance, you can define a unique class and then apply it based on certain conditions

// Define the styles for your custom class
.text-field-with-error {
    border: 1px solid;
    border-color: #c4c4c4;
    outline: 1px solid $primary-color !important;
    outline-offset: 1px;
}

In your JSX code, you can conditionally add the custom class like this:

<TextField className={hasError ? "text-field-with-error" : ""} />

Answer №2

To incorporate the error prop with the <TextField />, simply pass it as an attribute.

For a practical example, check out this demo or consult the Material-ui documentation.

<TextField
  error
  id="outlined-error-helper-text"
  label="Error"
  defaultValue="Hello World"
  helperText="Incorrect entry."
/>

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

implement adding a division element to the DOM using the append

I am facing an issue with this particular code. The intended functionality is to create multiple divs in a loop, but it seems to be dysfunctional at the moment. Upon clicking, only one div appears and subsequent clicks don't trigger any response. < ...

Accessing response headers in grpc-webWould you like to know how to

While utilizing grpc-web in my React app and making a call to the endpoint, I encountered an error: Error: Response closed without grpc-status (Headers only) getCurrent(callback: (user: User | null, err: ServiceError | null) => void) { const reques ...

Link a function to a button in a 3rd party library

Whenever I click a button, there is a possibility of an alertify alert window appearing randomly. The alertify alert popup serves as a more aesthetically pleasing alternative to the traditional javascript Alert. Alertify library Below is a snapshot depic ...

What are some creative ways to incorporate images into SVG paths?

Check out my JSFiddle here. I'm attempting to position this image in the center of my arc. My initial thought was to use .attr("fill","url('somePicture')"), but so far, no luck with that approach. const width = 700; const height = 600; con ...

How can I import an excel spreadsheet using Javascript, or alternatively, convert an excel file to a text document

I have been updating my file upload page to handle both text and excel files. However, when trying to read excel files with my current code, I am getting strange output. It seems that my function, which was originally designed for text files, needs modific ...

The table's width exceeds the appropriate size

Take a look at the code snippet below <%-- Document : index Created on : Feb 7, 2014, 1:03:15 PM --%> <%@page import="java.util.Map"%> <%@page import="java.util.Iterator"%> <%@page import="analyzer.DataHolder"%> <%@p ...

Issue with grid element not properly scaling using the transform:scale property

I have encountered an issue where a simple grid, with the gaps set to 0, displays a small line when I apply the transform:scale(1.5) css property. I am unsure if this is a bug or if I am doing something incorrectly. Interestingly, the result in Firefox dif ...

Executing a Function within UseEffect

I need help calling the function onSaveInputValue within the useEffect to make sure that the value is passed to the childInputValue hook whenever the page loads. const onSaveInputValue = (value) => { setChildInputValue(value); consol ...

Incorporate a personalized JavaScript code segment during the Vue build process

I am currently working with Vue CLI and I need to include a custom javascript section in the default template when I release my project. However, I do not want this section to be included during the debugging phase. For example, I would like to add the fo ...

Animating CSS using JavaScript

Recently diving into the world of JavaScript, I've taken on the challenge of creating an analog clock. I began by crafting the second hand using CSS but now I'm eager to transition it to Javascript without relying on jQuery or any other JS framew ...

What is the process for updating parameters before finalizing a route in Vue.js?

I have set up a route with a value parameter: routes.push({ name: 'test', path: '/test/:value', component: resolve(__dirname, 'src/pages/test.vue'), }); Now, I want to modify the route so that it also include ...

Is it time to swap out those divs for tables in your email template?

I have set up my template like this and I am questioning whether I should replace every div with a table. Let's start with the first div in the example. Do I really need to create a new table element, followed by tr and td tags just for a banner? I u ...

Concealing specific DIV elements (unfortunately not nested)

Currently, I am dealing with pre-existing code that is automatically generated and needs to adhere to a specific format: <div id="TITLE1"></div> <div id="div-1"></div> <div id="div-2"></div> <div id="div-3"></d ...

Looking to display the view source of an HTML page, but it keeps redirecting to another site when I try. Anyone know how to diagnose and fix this issue?

Can anyone assist me in displaying the HTML source of a page without it redirecting to another site? Here is the URL: ...

Utilizing v-for and CSS Grid to showcase data effectively

I'm having trouble organizing my Vuex data with CSS GRID. It's turning out messy. My setup includes two columns: the first one for labels and the second for values. {{$store.state.stepOne.textfield[idx].label}} The code above is used to displa ...

Error persisting unique key property despite implementation of unique key in table row

I'm having trouble resolving this issue. I've assigned a unique ID, but React is still showing error messages. I attempted to address it with each element individually, but then the problem of duplicates arises. <table> ...

Is there a way to utilize two onChange functions within one component?

I'm having trouble utilizing two onChange functions within the same component. I attempted to combine them, but I ran into an issue because one is using useState and the other is a const function. Below is my code snippet: const signup = () => { ...

Utilizing the getJSON Method to Automatically Fill a Dropdown Selection Element

I am looking to populate a dropdown select menu with bank names and IIN numbers obtained from the following JSON: JSON Data : {"status":true,"message":"Request Completed","data":[{"id":1,"activeFlag":1,"bankName":"Union Bank of India","details":"Union Ba ...

Why is the column width on this Tumblr page constantly flickering?

Seeking assistance with a minor issue on my Tumblr page - the content column seems to be flickering on mouseover, shifting between full width and its original programmed width. Any insight on the CSS causing this? Much appreciated! Check it out here (Dis ...

Unable to modify the active property of the specified object as it is read-only

Presented here is the interface: export interface ProductCommand extends ProductDetailsCommand { } This is the ProductDetailsCommand interface: export interface ProductDetailsCommand { id: string; active: boolean; archive: boolean; title: ...