18

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?

1
  • Trim the string and check if the length is 0. Commented Sep 22, 2016 at 3:41

2 Answers 2

41

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Why would you check both? If name == "" then the length is 0.
@EvanTrimboli completely forgot the trim(), edited
this.props.description.trim().name ?
@EvanTrimboli Slipped through again! Thanks :)
Which comes back to the original point, why would you check them both? If name.trim() == "" then length must be 0.
|
6

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.

4 Comments

When is the length property equal to a string?
Why would trim() ever equal " "?
Thanks, I modified my answer.
Nested block is redundant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.