I have the following example:
<h1>{errors.email?.message || ' '}</h1>
Which means: If there is an error message, display it, else display a normal space.
The problem I faced is that react shows the error if it's available, else it doesn't show anything, in other words, the space string is always ignored and will be never displayed.
Why is this happening and how can I show a string that contains only a whitespace
CodePudding user response:
You'll be able to display only whitespace by using the white-space
property:
function App() {
return <h1 style={{ whiteSpace: "pre-wrap" }}>{" "}</h1>;
}
ReactDOM.render(<App />, document.getElementById("root"));
h1 { /* so we can see the h1 */
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
CodePudding user response:
For a ternary in react use : instead of ||. That way it will use the empty string if nothing is in the error message. Check this simple stack on how that is either shown or not based on a state object.
Edit: For optional chaining your logic should be working fine. We might need more data though. Here you can see that the white space is showing on the first one. The second one doesn't include a white space.
What does errors.email?.message
print to the console?