Reputation: 1404
I have a select element in HTML and I would like to give it a placeholder. I want this placeholder to be selectable (so no options are selected).
Because it is a placeholder I want the option text to be grey, and when the option is selected I want the select element's text to also be grey.
There are many questions that solve part of this problem, but none that offer a functional solution (that I can find).
Below is an example of the desired outcome (see the Campus dropdown).
I am using React for the project, and have looked at the React-select package but cannot find a way to implement it like this.
Upvotes: 0
Views: 1344
Reputation: 1074595
You can do this with CSS by making the option color grey with a selector, making the select grey when the default is selected, , and making other options a specific color (so they remain that color when the select
is grey rather than inheriting grey from it). Here's an example:
const {useState} = React;
function Example() {
const [value, setValue] = useState("");
const onChange = ({currentTarget: {value}}) => {
setValue(value);
};
return <select size="1" className={value ? "" : "greyed"} value={value} onChange={onChange}>
<option value="">Default</option>
<option value="A">Option A</option>
<option value="B">Option B</option>
</select>;
}
ReactDOM.render(<Example/>, document.getElementById("root"));
/*
We have this so that when the select is greyed, its options aren't
*/
select option[value] {
color: black;
}
/*
Grey-out an element with the class, and option elements with blank values
*/
.greyed, select option[value=""] {
color: grey;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
Upvotes: 1