lost9123193
lost9123193

Reputation: 11030

Check for empty string in JSX

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

Answers (2)

Andrew Li
Andrew Li

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

Hieu Tran
Hieu Tran

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

Related Questions