From what I can see, React only modifies the relevant css value (in this case background-color) in two cases: 1. when a truthy value is replaced with a falsy one (for example, when "r" is changed to "") or when a different valid color value is entered (for example, changing "darred" to "darkred").
In order to have the behavior you're looking for (switching from red to white when "red" is repalced with "re"), you must include a check of whether the entered string is a valid color value. I copied a function that makes this check from this stackoverflow issue Javascript - check if string is valid CSS color? and modified your component to the following:
function App() {
const [userInput, setUserInput] = useState("");
const onChange = (e) => {
setUserInput(e.target.value);
};
function isColor(strColor) {
var s = new Option().style;
s.color = strColor;
return s.color == strColor;
}
return (
<div className="App">
<label htmlFor="colorInput">Selected Color: </label>
<input onChange={onChange} value={userInput} id="colorInput" />
<Box color={isColor(userInput) ? userInput : ""} />
</div>
);
}
Seeing as how this check is not done automatically by React, my best guess as to what's going on under the hood is that React checks if the new value is truthy and if it is a color. If the value is truthy but not a color value, the css is not modified. If the new input value is falsy, React switches the color to white since the value is now evaluated as null (what you were expecting when you switch from "red" to "re).