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.
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.
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:
1npx create-react-app react-read-more
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:
1import React from 'react';
2import './App.css';
3
4
5function App() {
6 return(
7 <div className="App">
8
9 </div>
10 )
11}
12
13export default App;
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.
Inside the root directory, run :
1npm start
This will spin up a local development server (usually on port 3000) and you can see all your changes live on the browser.
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.
1import React from 'react';
2import './App.css';
3
4function App() {
5
6 return (
7 <div className="App">
8 <input type="text" placeholder="Enter a string..." />
9 <button >Format String</button>
10 <b><p></p></b>
11
12 </div>
13 );
14}
15
16export default App;
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.
1import React,{useState} from 'react';
2import './App.css';
3
4function App() {
5 const [string,setString]=useState('');
6 const [isDisplay,setDisplay]=useState(true);
7 const handleChange=(e)=>{
8 setDisplay(false);
9 setString(e.target.value);
10 }
11 const formatString=()=>{
12
13 }
14 return (
15 <div className="App">
16 <input type="text" placeholder="Enter a string..." onChange={handleChange}/>
17 <button onClick={formatString}>Format String</button>
18 <b><p>{isDisplay && string}</p></b>
19
20 </div>
21 );
22}
23
24export default App;
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 const formatString=()=>{
3 setDisplay(true);
4 let temp=string;
5 temp=temp.replace(/\s+/g, '');
6 setString(temp);
7 }
8 ...
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:
1import React,{useState} from 'react';
2import './App.css';
3
4function App() {
5 const [string,setString]=useState('');
6 const [isDisplay,setDisplay]=useState(true);
7 const handleChange=(e)=>{
8 setDisplay(false);
9 setString(e.target.value);
10 }
11 const formatString=()=>{
12 setDisplay(true);
13 let temp=string;
14 temp=temp.replace(/\s+/g, '');
15 setString(temp);
16 }
17 return (
18 <div className="App">
19 <input type="text" placeholder="Enter a string..." onChange={handleChange}/>
20 <button onClick={formatString}>Format String</button>
21 <b><p>{isDisplay && string}</p></b>
22
23 </div>
24 );
25}
26
27export default App;
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.
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>
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.
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.