Removing Unwanted Whitespace in React


7 Shares
facebook sharing button Share
twitter sharing button Tweet
linkedin sharing button Share
pinterest sharing button Pin
email sharing button Email
sharethis sharing button Share

Problem: Unwanted whitespace in the browser in a React app.

 Download The Notes Here


I came across this issue when I was working on a project in React. You can see here that there is an extra space added between the words "click" and "here", and between "here" and the period.

Detail of Home Page


This is what the code looks like. The indentation is from the text editor.

Code Detail


And even if you remove the whitespace manually in the text editor, the result is the same and you still get the extra spaces in the browser.

Code Detail


1. Here is a hack you can try. Put the text that has the extra whitespace in the browser inside a span tag. In this example, the word “here” (line 26) and the final period (line 28) have been put inside a span tag.

Code Detail


2. Next, add inline styling for each of these and do a marginLeft of "-10px" (lines 26 and 28):

Code Detail


And now the unwanted whitespace has been removed from between the word "click" and the period. But now there is no space between the words "click" and "here":

Detail of Home Page


3. The only thing left to do is to manually add a space in the text editor before the word here (line 26):

Code Detail


And now the problem is solved. Now there is just one space between the words "click" and "here". And there is no longer any unwanted whitespace:

Detail of Home Page