So I'm using material-Ui on my react project, I'd like to set a placeholder that's only difference from a selected item is the color being grey instead of black
<Select
name="answer"
value={values.answer}
onChange={handleChange}
onBlur={handleBlur}
displayEmpty
className={styles.selectEmpty}
>
<MenuItem
value=""
disabled
className={styles.selectPlaceholderText}
>
Answer
</MenuItem>
<MenuItem value={"1"}>1</MenuItem>
<MenuItem value={"2"}>2</MenuItem>
<MenuItem value={"3"}>3</MenuItem>
<MenuItem value={"4"}>4</MenuItem>
</Select>
This approach gives me something very close to what I need, the problem is that:
selectPlaceholderText
doesn't seem to do the trick.The ::placeholder selector selects form elements with placeholder text, and let you style the placeholder text. The placeholder text is set with the placeholder attribute, which specifies a hint that describes the expected value of an input field.
You can change the Select placeholder color by using CSS. Use id only to change the color or placeholder and if you want to change the color of the option then use the option also.
There is no placeholder attribute in 'select' tag but it can make the placeholder for a 'select' box. There are many ways to create the placeholder for a 'select' box.
<input type="text" placeholder="A red placeholder text..">
Styling via a className
on the MenuItem
does not work because the default display of the selected menu item displays its children. If you placed a div
or span
around the text within the MenuItem
, it would work to add styling to that.
If you don't want the item in the list at all, then you want to use the renderValue prop to control the rendering of the selected item. In the working example below, renderValue
is set to undefined
when a value is selected in order to get the default behavior, but when the value is empty it renders the Placeholder
element.
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import MenuItem from "@material-ui/core/MenuItem";
import Select from "@material-ui/core/Select";
const usePlaceholderStyles = makeStyles(theme => ({
placeholder: {
color: "#aaa"
}
}));
const Placeholder = ({ children }) => {
const classes = usePlaceholderStyles();
return <div className={classes.placeholder}>{children}</div>;
};
export default function SimpleSelect() {
const [answer, setAnswer] = React.useState("");
return (
<Select
value={answer}
displayEmpty
onChange={event => setAnswer(event.target.value)}
renderValue={
answer !== "" ? undefined : () => <Placeholder>Answer</Placeholder>
}
>
<MenuItem value={"1"}>1</MenuItem>
<MenuItem value={"2"}>2</MenuItem>
<MenuItem value={"3"}>3</MenuItem>
</Select>
);
}
Related answers:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With