In React, the input is consistently considered 'valid'

I have a React component that looks like this

export const SearchBar = ({
  searchInput,
  updateSearchKeyword,
}: SearchBarProps) => {
  const dummy = "";
  return (
    <div className={`${styles.container} `}>
      <input
        className={`${styles["search-bar"]} `}
        type={"text"}
        value={dummy}
        title="search"
        placeholder="Search..."
        onChange={(e) => updateSearchKeyword(e.target.value)}
      />      
    </div>
  );
};

Now, I want to apply CSS changes when the input field has text. My CSS code is as follows

.search-bar:valid {
  color: red;
}

But the color is always red, meaning the input is always considered 'valid'

I have tried

.search-bar[type="text"]:valid {
  color: red;
}

and also added a pattern in the component, but the issue persists. How can I resolve this?

Note: I am using modules.css, so the class names may appear unusual, but they are functioning correctly for other properties.

Answer №1

When it comes to styling your components, remember that simply declaring a class name will not update the style dynamically. If you want to change the color of an input based on certain conditions, you'll need to utilize state and event handling.

For instance, instead of just assigning an empty string to the value of an input, you should use useState to manage the value dynamically:

const [inputValue, setInputValue] = useState('');

Then, you can update the input value and handle style changes like this:

value={inputValue}
onChange={(e) => setInputValue(e.target.value)}

To change the style based on the input value, you can define a handleChange function that updates the state and checks for conditions:

const handleChange = (value) => {
  setInputValue(value);

  if (value !== '') {
    // Change the style of the input (e.g. color)
  }
}

Instead of manually manipulating the DOM, consider using state to manage styles:

const [inputStyle, setInputStyle] = useState(`${styles["search-bar"]}`);

Then, you can update the style by setting the state:

setInputStyle(`${styles["search-bar-blue"]}`);

Additionally, for validation, you can define a CSS pattern to enforce specific criteria:

<input pattern="[a-z]+" type.../>

This pattern will only validate true if the input consists of lowercase letters only.

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

What is causing this issue with my jQuery UI animation?

Below is the HTML code snippet: <div id="menu_status_item"> <span class="menu_status_bar"></span> </div> Here is the CSS code: #menu_status_item { margin-top: 40px; width: 100%; } .menu_status_bar { margin-le ...

Declaring properties for an interface

I've recently started using Typescript and I'm facing a problem with some interface props. There is an error message that says "Property 'services' does not exist on type 'IntrinsicAttributes & AkkordionProps[]", I'm confu ...

The React Hook Form's useFieldArray feature is causing conflicts with my custom id assignments

My schema includes an id property, but when I implement useFieldArray, it automatically overrides that id. I'm utilizing shadcn-ui Version of react-hook-form: 7.45.0 const { fields, append, remove, update } = useFieldArray<{ id?: string, test?: n ...

Struggling to reveal concealed items on a webpage using jQuery and attempting to cycle through an array without success

Looking to display or hide certain sections on a page based on specific conditions. I want to only show the sections of the page that contain words from the conditionsToShow array. function hideWorkflowConditions() { // initially hide the elements ...

Targeting all children instead of just the odd ones when using `nth-child(odd)`

In the portfolio, I have a unique requirement where every odd entry should be reversed. These projects are generated dynamically from an array and passed into the component through props. To style it, I'm utilizing styled-components. However, I&apos ...

How can I move one of the multiple input fields to the top right side?

I am facing an issue and need some assistance. I have created a page with multiple font controls, but in my prototype design, there is a field on the right side where the inputs are positioned at the top and on the right. How can I achieve this? I have cr ...

React safeguarding sensitive data in production builds

In the process of developing a React app with Docker and Jenkins for deployment, one question arises: How can I securely provide environment variables to this static application? Shown below is my current Dockerfile: # Stage 1: building the React app FRO ...

The constant contract that was exported encountered an error stating "The provider does not possess a request or send method to utilize."

I'm currently working on creating a helper class to instantiate the necessary contracts for my dapp. At the moment, I am focused on exporting a contract instance of dai for payment purposes. Below is the code snippet for dai.js: import Web3 from &apos ...

What is the process for modifying a Joomla plugin?

Just starting out with Joomla development and recently installed Joomla 2.5 on my local computer for some practice. I have a question about editing Joomla plugins - specifically the layout of the Content - Pagebreak plugin (the pagination that appears wh ...

Tips for creating a responsive navigation bar using your own custom CSS styling

While working on a website using bootstrap, I encountered an issue with responsiveness when adjusting the text size and gap of the navigation items. By increasing the size and adding a gap through fs-4 and style="gap: 10vh;", the default small si ...

A problem with centering a popup window using the CSS transform() function

Discovered a clever technique for creating a centered popup window in an application ( http://www.w3.org/Style/Examples/007/center ). Neat and simple code implementation ( http://jsfiddle.net/babaca/6rwL0v0c/22/ ). html <div class="__holder"> & ...

Enabled the swcMinify setting to true in Next.js version 12

Recently, I made the decision to remove my babelrc file in favor of the new rust compiler, which is being endorsed by Vercel. However, this change caused my build process to break down. The only content within my babelrc was: { "presets": [&quo ...

What is the purpose of Component.spec.tsx files in React development?

As I delve into the code within the Material UI React library, one particular aspect that stands out is the use of Component.spec.tsx, specifically looking at the spec file found here. import * as React from 'react'; import FormLabel, { FormLabel ...

What is the best way to add animation to switch between table rows?

I am looking to add animation effects when table rows appear and disappear. Initially, I attempted using a CSS transition, but it did not work due to the change in the display property. Subsequently, I opted for an animation, which provided the desired o ...

Tips for tidying up duplicated typescript content sourced from a pre-existing library

Seeking guidance on implementing best practices and gaining a better understanding of my approach. After discovering the library react-google-calendar-api, I successfully installed it using npm in my React project. However, I wanted to expand its function ...

Display Bootstrap 4 Carousel thumbnails on the right side rather than the bottom

I have implemented the Bootstrap 4 carousel slider with the help of this example. In the example provided, I am trying to align the bottom thumbnails to the right side along with the thumbnail text, similar to the image attached below. https://i.sstatic. ...

Update the position of a div when an element becomes visible

Currently, I have 3 titles each with a button underneath to reveal more information about the subject. To toggle the visibility of the content, I have implemented a script that shows or hides the corresponding div when the button is clicked. On smaller de ...

When hovering or mousing over, the text remains stationary and does not follow the scroll bar movement within the

A method I am using involves displaying additional data on hover for a shortened header, like this: Hover behavior However, the text shifts across the page when the scrollbar is used, as shown here: Scrollbar interaction This table showcases HTML, CSS, ...

Tips for receiving feedback when uploading multiple images

I've been facing challenges with receiving a response when uploading multiple images using the API. Despite getting a valid response when uploading a single image, I'm not getting the expected response for multiple uploads. Below is my code: fil ...

Determine the precise x and y coordinates of a centered element using JQuery

How can I determine the exact left and top positions of an element? The parent container has text-align: center, causing potential confusion when there are multiple elements on the bottom row. For instance, the first one may have a position of 0px instea ...