Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 934
lost9123193 Avatar asked Sep 22 '16 03:09

lost9123193


People also ask

How do you check if string is empty React JS?

To check if a string is empty in React, access its length property and check if it's equal to 0 , e.g. if (str. length === 0) {} . If the string's length is equal to 0 , then the string is empty, otherwise it isn't empty.

How do you check for empty strings?

You can determine if a string is an empty string using the == operator. The empty string is a substring of every other string.

What is empty tag in JSX?

The React framework offers a shorthand syntax for fragment components that appears as an empty tag: <></> . While it is supported in JSX syntax, it is not part of the HTML standard and thus is not supported natively by browsers.


1 Answers

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.

like image 164
Andrew Li Avatar answered Sep 22 '22 14:09

Andrew Li