How to useConditional Rendering in ReactJS

In the approach for modifying the color of placeĀ­holder text in React, we use state to track a condition (for example, a button click). Based on this condiĀ­tion, they dynamĀ­ically assign a CSS class to the input element, thereby altering the color of the placeĀ­holder text.

Example: This example shows the use of the above-explained approach.

Javascript




// App.js
  
import React, { useState } from "react";
import "./App.css"; // Import your CSS file
  
const App = () => {
    const [isRed, setIsRed] = useState(false);
  
    const togglePlaceholderColor = () => {
        setIsRed(!isRed);
    };
  
    return (
        <div className="container">
            <h2 className="heading">w3wiki</h2>
            <input
                type="text"
                placeholder="Enter your text here"
                className={`input ${
                    isRed ? "red-placeholder" : ""
                }`}/>
                  
            <button
                className="button"
                onClick={togglePlaceholderColor}>
                Toggle Placeholder Color
            </button>
        </div>
    );
};
  
export default App;


CSS




/* App.css file*/
  
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
}
  
.heading {
    font-size: 34px;
    color: green;
}
  
.input {
    width: 250px;
    height: 40px;
    padding: 10px;
    font-size: 16px;
    color: #333;
    border: 2px solid green;
    border-radius: 15px;
    outline: none;
}
  
.red-placeholder::placeholder {
    color: red;
}
  
.button {
    padding: 10px 20px;
    font-size: 16px;
    border: none;
    border-radius: 5px;
    outline: none;
    cursor: pointer;
    background-color: #0074d9;
    color: #fff;
    margin-top: 10px;
}
  
.red-button {
      /* Red button color when condition is met */
    background-color: red
}


Output:



How To Change Placeholder Color In ReactJS ?

In this article, weā€™ll explore two different approaches to changing the placeholder color in ReactJS.

To change the color of the placeĀ­holder text, the CSS ::placĀ­eholder pseudo-element is primarily utilized. This handy pseudo-element enables us to style the placeĀ­holder text within an input field.

Syntax

::placeholder {
color: yourColorValue;
}

Similar Reads

Prerequisites

Introduction to React React Components ReactJS Hooks NPM or NPX...

Steps to Create React Application

Step 1: Create a react application by using this command...

Approach 1: Using CSS Styling

...

Approach 2: Using Conditional Rendering

In this approach, it sets the placeholder text color to crimson using an inline