Reputation: 11030
Is there a way in React/JSX to check if a user's input string is empty?
Component.js
{((this.props.description.name ==" ")||(this.props.description.name.length==""))?
This condition works when a user inputs nothing or an empty string that is 1 space long, but if the empty string is more than 1 space long it fails. Is there a trick with JSX to check this or should I handle this in my reducer?
Upvotes: 18
Views: 85987
Reputation: 57964
You could check for trimmed string:
{this.props.description.name.trim() == ""}
This trims the string (which removes whitespace and newlines) and then check is if it's an empty string. Here's a CodePen demonstration.
Upvotes: 41
Reputation: 364
You can easily to trim the text and compare with empty string. Let try:
{((this.props.description.name.trim() =="") || (this.props.description.name.trim().length==0))
to see how it's work. I've seen you remind about Reducer? You are using Redux, aren't? If you use Redux, for handling form data, you could use Redux Form (https://github.com/erikras/redux-form) to save your time.
Upvotes: 6