Best practice when adding whitespace in JSX - javascript

I understand how (and why) to add a whitespace in JSX, but I am wondering what's best practice or if any makes any real difference?
Wrap both elements in a span
<div className="top-element-formatting">
<span>Hello </span>
<span className="second-word-formatting">World!</span>
</div>
Add them on one line
<div className="top-element-formatting">
Hello <span className="second-word-formatting">World!</span>
</div>
Add space with JS
<div className="top-element-formatting">
Hello {" "}
<span className="second-word-formatting">World!</span>
</div>

Because &nbsp causes you to have non-breaking spaces, you should only use it where necessary. In most cases, this will have unintended side effects.
Older versions of React, I believe all those before v14, would automatically insert <span> </span> when you had a newline inside of a tag.
While they no longer do this, that's a safe way to handle this in your own code. Unless you have styling that specifically targets span (bad practice in general), then this is the safest route.
Per your example, you can put them on a single line together as it's pretty short. In longer-line scenarios, this is how you should probably do it:
<div className="top-element-formatting">
Hello <span className="second-word-formatting">World!</span>
<span> </span>
So much more text in this box that it really needs to be on another line.
</div>
This method is also safe against auto-trimming text editors.
The other method is using {' '} which doesn't insert random HTML tags. This could be more useful when styling, highlighting elements, and removes clutter from the DOM. If you don't need backwards compatibility with React v14 or earlier, this should be your preferred method.
<div className="top-element-formatting">
Hello <span className="second-word-formatting">World!</span>
{' '}
So much more text in this box that it really needs to be on another line.
</div>

You can use the css property white-space and set it to pre-wrap to the enclosing div element.
div {
white-space: pre-wrap;
}

I tend to use
It's not pretty but it's the least confusing way to add whitespace I've found and it gives me absolute control over how much whitespace I add.
If I want to add 5 spaces:
Hello <span className="second-word-formatting">World!</span>
It's easy to identify exactly what I'm trying to do here when I come back to the code weeks later.

You can add simple white space with quotes sign: {" "}
Also you can use template literals, which allow to insert, embedd expressions (code inside curly braces):
`${2 * a + b}.?!=-` // Notice this sign " ` ",its not normal quotes.

You can use curly braces like expression with both double quotes and single quotes for space i.e.,
{" "} or {' '}
You can also use ES6 template literals i.e.,
` <li></li>` or ` ${value}`
You can also use &nbsp like below (inside span)
<span>sample text </span>
You can also use &nbsp in dangerouslySetInnerHTML when printing html content
<div dangerouslySetInnerHTML={{__html: 'sample html text: '}} />

I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:
<p>
Hello {
<span>World</span>
}!
</p>
or
<p>
Hello {}
<span>World</span>
{} again!
</p>
Each of these produces clean html without additional or other extraneous markup. It creates fewer text nodes than using {' '}, and allows using of html entities where {' hello & goodbye '} does not.

You don't need to insert or wrap your extra-space with <span/>. Just use HTML entity code for space -
Insert regular space as HTML-entity
<form>
<div>Full name:</span>
<span>{this.props.fullName}</span>
</form>

use {} or {``} or to create space between span element and content.
<b> {notif.name} </b> <span id="value"> { notif.count }{``} </span>

Despite using this is a neat approach: using the <Fragment> tag to insert HTML inside a variable, which allows the creation of a custom spacer to be used in JSX.
Import { Fragment } ...
import { Fragment } from "react"
Create the variable..
const space = <Fragment> </Fragment>
Note: it can also be done with <span> instead of <Fragment>
Use like so..
return (
<div> some text here {space} and here... </div>
)

If the goal is to seperate two elements, you can use CSS like below:
A<span style={{paddingLeft: '20px'}}>B</span>

Related

Save line breaks from String in JavaScript object to transfer over to breaks in HTML

sorry if this a pretty basic question but I'm trying to store a multi-paragraph chunk of text in an object in a Pinia store to be converted to text in HTML, but I can't figure out how to transfer paragraph breaks through the Pinia store.
export const useContentStore = defineStore('contentStore', {
state: () => {
return {
guides: [{
description: 'Paragraph one. Paragraph two. Paragraph three.',
}],
}
},
})
<template>
<main class="content-page">
<body>
<p>{{ content.description }}</p>
</body>
</main>
</template>
I'd like there to be some space between each paragraph, I don't know if that would be adding another line between them or something different. I've already tried escaping like \n, adding <br> tags in the text, and using template literals.
This is what my end goal is:
Paragraph one.
Paragraph two.
Paragraph three.
Thanks for any help you can give!
p {
white-space: pre-wrap
}
<p>
Paragraph one.
Paragraph two.
Paragraph three.
</p>
As you can see above, if you use css property white-space: pre-wrap, it can do what you ask, but be carefull, it may cause other weird interactions.
It will preserve whitespaces, newlines, tabs and <br />.

Angular removes leading whitespace when rendering

At work, I am developing an Angular component that displays a string from its input on the rendered HTML page.
The HTML for displaying the string looks something like this:
<span>{{value}}</span>
where value comes from this.value in the Angular code. For normal strings this works OK, but I have found that Angular strips out leading whitespace. Now I know that HTML itself compresses multiple whitespace into one when rendering the HTML into a visible page, but the whitespace is removed from the HTML itself.
I have verified that the string in the Angular code contains whitespace:
console.log("The string is: [" + this.value + "]");
prints out The string is: [ Hello world!] on the web console. But what appears on the rendered HTML page is:
<span>Hello world!</span>
How can I fix this?
Even if Angular preserves the whitespace, which I assume it is doing, html will strip it down. You have two option to either use tag or do it via css as shown below:
No Preservation <br/>
<span> Hello world! </span><br/>
<span> Hello world! </span>
<br/>
With Pre tag
<pre>
<span> Hello World! </span>
</pre>
<br/>
With Css white-space: pre<br/>
<span style="white-space: pre;">
Hello World! </span>
One of the options is to use a non-breaking whitespace like this const value = ' Hello World!'

JavaScript string: get content of two standing next to each other pieces of content and wrap them together

I'm trying to create a small script that would wrap some parts of text from e.g. <p> tag like this one: <p>... 'displayed text'[popup content] ...</p> in a span wrapper.
The end result would look like this:
<span class='wrapper'>
displayed text
<span class='popup'>popup content</span>
</span>
At the moment I'm able to find and replace the text between apostrophes like this:
some_string.replace(/'(.*?)'/g,'<span>$1</span>');
But I would really like to wrap the popup content part first and then wrap it together with displayed text inside the wrapper element.
Would that be possible?
Sure - how about this?
some_string.replace(/'(.*?)'\[(.*?)\]/, "$1<span class='popup'>$2</span>");
Add a \s* between the two parts of the regex if they could be separated by whitespace:
/'(.*?)'\s*\[(.*?)\]/

Raw HTML is getting rendered on DOM in React component

I am getting below response from the API, and I want to convert it into proper html and would like to render it on dom, but it is rendering raw html and special characters.
example api response:
resp = {
body: "<p>Cali Thirty Seven turned what appeared to be certain defeat into an exhilarating and much-deserved victory late Saturday afternoon at Gulfstream Park. She reasserted herself after relinquishing the lead to 8-5 favorite Stormy Victoria to successfully defend her title in the $100,000 Powder Break Stakes.</p>\r\n<p>"
}
In the react component I am rendering it in the following way:
<p
className="newsDescription"
dangerouslySetInnerHTML={{ __html:this.props.story.desp }}
/>
I tried to escape html but it is not working.
You have to replace whatever html characters you have in your string to the corresponding tags. Since in your example you only have "<p> (which correspond to <p>) you can do this:
validate if this.props.story.desp has a value a is a string and then replace:
<span
className="newsDescription"
dangerouslySetInnerHTML={{ __html: this.props.story.desp.replace(/</g, '<').replace(/>/g, '>')}}
/>
This will generate a <span> element with a <p> element (the paragraph element coming from your API) inside the <span> with your text. Also, notice that this will replace all occurrences for creating the paragraph tags.
Unfortunately there is no generic vanilla javascript function for replacing all possible tags.
Note that I changed the <p> tag to a <span> because block elements should not have other block elements inside. Have a look at this question in SO.

Preserve formatting of text using letterings.js

Is there a way to preserve formatting (e.g. bold, italic) of text when using the letterings.js plugin? I am using the "word" wrapping function (https://github.com/davatron5000/Lettering.js/wiki/Wrapping-words-with-lettering%28%27words%27%29) and it seems to destroy any formatting made of the text.
Here's an example:
<div class="text-block">This is a <i>sentence</i> <b>with <i>formatting</i></b>.</div>
After using letterings.js, it turns into:
<div class="text-block">
<span class="word1">This</span>
<span class="word2">is</span>
<span class="word3">a</span>
<span class="word4">sentence</span>
<span class="word5">with</span>
<span class="word6">formatting.</span>
</div>
This is the function I'm using in jQuery:
$('.text-block').lettering('words');
I've found that I can preserve bold or italic (unfortunately not both) doing this:
$('.text-block b').lettering('words');
-OR-
$('.text-block i').lettering('words');
You can't use both ( i.e. $('.text-block b,.text-block i') ) at the same time.
If it's not possible with letterings.js, is there another plugin or method to wrap each word in spans but preserve the formatting?
If you change the method in line 15 from .text() to .html(), you can use
$('.text-block').lettering('words');
as is and it will not strip the tags.
Use this link to get the source:
https://gist.github.com/klatchbaldar/6956474

Categories

Resources