Author avatar

Gaurav Singhal

Render a String with Non-breaking Spaces in React

Gaurav Singhal

  • Jun 14, 2020
  • 7 Min read
  • 90 Views
  • Jun 14, 2020
  • 7 Min read
  • 90 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

Every framework aims to make the life of a developer easier. React has successfully done so with its easy-to-understand component architecture and the ability to write plain old vanilla JavaScript inside a component. The most crucial criterion that sets a frontend JavaScript framework apart is its capability to combine the benefits of a regular JavaScript application with its own. You can write JavaScript in a React component to do almost anything you want, such as DOM manipulation, creating data models using objects, making async calls, etc.

This guide explores the solution to a simple problem often encountered while dealing with strings: rendering them without spaces using some simple JavaScript and a neat CSS hack. It explores s use case in which you want to render a string without any empty spaces using the replace() method in JavaScript.

Dealing with Strings

Every programming language makes working with strings tricky and daunting. This is because strings vary in format, length, and the types of characters embedded. A single typo while entering a string can lead to a lot of breakages in the code, which is why validating strings on the frontend is highly important. Besides, spamming input fields on your application is much easier when the type of the field is set to text. The gibberish entered by the user can easily ruin your frontend data models, causing major bugs in your app and, in some cases, causing it to crash.

Creating an Empty Project

Make sure you have Nodejs and npm installed in your machine (at least version 8 or higher) along with a code editor and a web browser (preferably Chrome or Firefox).

Create a new project using create-react-application:

1
npx create-react-app react-read-more
shell

Cleaning up the Template

Remove the logo, App.css, and all their imports from App.js. Clean out the starter template inside the App component. Your App.js should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
import React from 'react';
import './App.css';


function App() {
  return(
      <div className="App">
          
     </div>
  )
}

export default App;
jsx

Note: Sometimes removing App.css might land you an error. In such cases, instead of deleting the App.css, keep it empty, or if you have already deleted it, create a blank CSS file under the same name in the root directory.

Setting up a Development Server

Inside the root directory, run :

1
npm start

This will spin up a local development server (usually on port 3000) and you can see all your changes live on the browser.

Creating the Template

Create a simple JSX template with an input field for the user to enter the string and a Format String button. When the user clicks the Format String button, display the formatted string, i.e., the string without any empty spaces on the DOM.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React from 'react';
import './App.css';

function App() {
 
  return (
    <div className="App">
      <input type="text" placeholder="Enter a string..." />
      <button >Format String</button>
      <b><p></p></b> 
      
    </div>
  );
}

export default App;
jsx

Adding State and Event Handlers

Import the useState hook from React to use state inside a functional component. Keep a state for storing the string entered by the user and another for toggling the display state of that string. This will tell React to display the formatted string on the page so you can see it.

Add an onChange handler that maps the string entered by the user to the state variable and an onClick handler that formats the string.

Inside the handleChange() method, toggle isDisplay to false and set the string to the string value entered by the user. Now the string to be formatted is stored by the state variable owned by the App component.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React,{useState} from 'react';
import './App.css';

function App() {
  const [string,setString]=useState('');
  const [isDisplay,setDisplay]=useState(true);
  const handleChange=(e)=>{
    setDisplay(false);
    setString(e.target.value);
  }
  const formatString=()=>{
  
  }
  return (
    <div className="App">
      <input type="text" placeholder="Enter a string..." onChange={handleChange}/>
      <button onClick={formatString}>Format String</button>
      <b><p>{isDisplay && string}</p></b>
      
    </div>
  );
}

export default App;
jsx

Formatting the String Using replace()

To remove the empty spaces from the string, use the replace() method in JavaScript. This method searches a string for a specified value and returns a new string replacing those values. It's commonly used to search a string for a regular expression and replace that expression with the desired substring.

1
2
3
4
5
6
7
8
  ...
      const formatString=()=>{
        setDisplay(true);
        let temp=string;
        temp=temp.replace(/\s+/g, '');
        setString(temp);
      }
  ...
jsx

Inside formatString(), set isDisplay to true and copy the string in a temporary variable. Search for any empty spaces using the given regex in the replace() method as the first parameter, and replace all its occurrences with an empty character. This renders the string with non-breaking spaces.

Finally, your App.js should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React,{useState} from 'react';
import './App.css';

function App() {
  const [string,setString]=useState('');
  const [isDisplay,setDisplay]=useState(true);
  const handleChange=(e)=>{
    setDisplay(false);
    setString(e.target.value);
  }
  const formatString=()=>{
    setDisplay(true);
    let temp=string;
    temp=temp.replace(/\s+/g, '');
    setString(temp);
  }
  return (
    <div className="App">
      <input type="text" placeholder="Enter a string..." onChange={handleChange}/>
      <button onClick={formatString}>Format String</button>
      <b><p>{isDisplay && string}</p></b>
      
    </div>
  );
}

export default App;
jsx

Test the application by entering any string in the input field with spaces in between, and hit the Format String button. You will see the resultant string rendered with non-breaking spaces on the page.

Using the No-wrap Property in CSS

It isn't always efficient to alter or edit the original string. Luckily, in some situations, you can use a neat CSS hack to display a string without any spaces. The white-space CSS property defines how white spaces can be handled inside an element. If your JSX element is such that the white spaces are equivalent to empty spaces in the string, you can simply set this property to nowrap.

1
<div style={{ whiteSpace: 'nowrap' }}>{string}</div>
jsx

Essentially, the nowrap attribute collapses all sequences of whitespaces into a single one, and text keeps rendering on the same line unless a line break is encountered.

Conclusion

In this guide, you learned how to handle strings with non-breaking spaces through the replace() method. You can use this method for formatting text on the page or handling a variety of form validations. The CSS solution discussed in this guide is not as reliable, as it depends on how the markup is written, the length of the text, its inherent styles, etc. Use it only when you are sure it won't break the styles or your DOM elements.

0