literal string with div tag - javascript

I have three strings and i want to concatenate them together, but one of them is within strong tag. The result is as below which is not as expected. What is the problem here?
Result:
There is no Colors for <strong>blah</strong> in the database.
Expected:
There is no Colors for blah in the database.
const fruitResult = 'There is no Colors for ';
const searchItem = `<strong>${fruitSearch}</strong>`;
const fruitResult1 = ' in the database.';
const fruitResult2 = 'No Data available.';
<div>
<h2>
{fruitSearch === ''
? `${fruitResult2}`
: `${fruitResult} ${searchItem} ${fruitResult1}`
}
</h2>
</div>
https://codesandbox.io/s/solitary-brook-q1rj93?file=/src/App.js

If you want to emit unescaped markup you can use dangerouslySetInnerHTML, but as it says on the tin you should only do this if you control and trust the source.
const html = `${fruitResult} ${searchItem} ${fruitResult1}`;
<div>
<h2 dangerouslySetInnerHTML={{ __html: html }} />
</div>
Here's a working fork of your sandbox demo.

Related

How to force a line break from string content?

I'm loading data for a page dynamically depending on the data I get from my backend , My code looks like this :
return (
<p className="font-mukta tracking-0.165 text-center lg:text-start text-32px md:text-44px xl:text-6xl font-medium pb-2 md:pb-0 xl:leading-snug">
{title}
</p>
if my title for example is: Lorem Ipsum is simply dummy text of the printing and I want to add a line break after a certain word in that text , for example a line break after the word simply but it's dynamic ,Is there anyway I can force a line break from the string itself for example by adding the html tag <br> or /n in the actual string but that doesn't really work , Any tips ?
Try using the replace method on the text variable to add a break tag after every occurrence of the particular word.
return (
<p className="font-mukta tracking-0.165 text-center lg:text-start text-32px md:text-44px xl:text-6xl font-medium pb-2 md:pb-0 xl:leading-snug">
{title.replace("word", "word <br>")}
</p>
if you are going to set the title with some html tags then it will escape all those and simply write "" as a string. To just use the html syntax in the text of tag use the dangerouslySetInnerHtml
const createMarkup = ()=>{
// add here the logic to replace that word with line break tags
const newtitle = title.replace('word','word <br>')
return {__html: newtitle}
}
return (
<p className="font-mukta tracking-0.165 text-center lg:text-start text-32px
md:text-44px xl:text-6xl font-medium pb-2 md:pb-0 xl:leading-snug" dangerouslySetInnerHTML={createTitle()} />
}
This is how I would do it-
import React from "react";
const Test = ({ title }) => {
//lets say we have to add a line break after the word simply
const index = title.indexOf("simply");
title =
title.slice(0, index) +
`simply<br>` +
title.slice(index + "simply".length + 1);
return <div dangerouslySetInnerHTML={{ __html: title }}></div>;
};
export default Test;
We can find the index of the string that we want to add a break after and then do the calculation as shown above which will help in manipulating the string. Now we can set it using the prop dangerouslySetInnerHTML as shown above.

Render HTML that is saved in and returned from Backend?

I'm working on a project where I get back a string from the backend, that contains some html. I'd now like to put this html into gatsby:
let htmlFromBackend = `<b>Hello there</b>, partner!`
return (
<div>
{htmlFromBackend}
</div>
)
However, this prints out the html as plain text, so what I see on the screen is literally:
<b> Hello there</b>, partner!
Whereas it should be
Hello there, partner!
How can I render this as proper html?
You can use dangerouslySetInnerHTML however be sure you trust the data coming from the backend as you don't get any protection from XSS attacks.
let htmlFromBackend = `<b>Hello there</b>, partner!`
return (
<div dangerouslySetInnerHTML={{ __html: htmlFromBackend }} />
)
You can use useRef hook and set the element's innerHTML:
const ref = useRef(null);
useEffect(() => {
let htmlFromBackend = `<b>Hello there</b>, partner!`;
ref.current.innerHTML = htmlFromBackend;
}, []);
return <div ref={ref} />;
Install html-react-parser
npm i html-react-parser;
And in the component
import Parser from 'html-react-parser';
let htmlFromBackend = `<b>Hello there</b>, partner!`
return (
<div>
{Parser((htmlFromBackend)}
</div>
)

How Can I Insert <span> To a Rendered Text In React?

I'm rendering some paragraphs using React. Inside those paragraphs there should be a span for footnotes. The best I got so far is that it rendered [object Object].
function ArticleItem() {
const articles = [
{
title: "title",
content: [
`Text based on this footnote <span>1</span>`,
`Another argument, here is my source <span>2</span>`
]
}
];
return (
<div className="article-container">
<h3> {articles[i].title} </h3>
{
articles[i].content.map(paragraph => (
<p>
{ paragraph }
</p>
)
}
</div>
);
}
Because you are creating a string with "<span>" instead of creating actual <span> HTML elements. What you are using is named jsx, which converts HTML tags to their corresponding document.createElement() (or similar, which in React has it own way).
If you want the content to be an HTML element and not a string, then create an HTML element:
function ArticleItem() {
const articles = [
{
title: "title",
content: [
<p>Text based on this footnote <span>1</span></p>,
<p>Another argument, here is my source <span>2</span></p>
]
}
];
return (
<div className="article-container">
<h3> {articles[i].title} </h3>
{ articles[i].content.map(paragraph => paragraph) }
</div>
);
}
Notice how I removed the string literal (``) and created an HTML element.
If the article content comes from an API call, then avoid using HTML tags inside strings. That's a bad practice actually. Always create the tags within the render() call and populate them with the API data you received.
Assuming the content array has to be supplied as raw HTML, a common solution is to use the dangerouslySetInnerHTML prop to render that HTML directly. You can introduce that to your <p> elements like this:
articles[i].content.map(paragraph => (
<p dangerouslySetInnerHTML={{ __html: paragraph }} />
))
A few other things to consider; I noticed a missing ) in your code after the <p> element of your map statement which will be causing a syntax error. Also, ensure that i is defined to an index in range of your articles array. Here's an example of each fix applied:
function ArticleItem() {
const articles = [
{
title: "title",
content: [
`Text based on this footnote <span>1</span>`,
`Another argument, here is my source <span>2</span>`
]
}
];
const i = 0;
return (
<div className="article-container">
<h3> {articles[i].title} </h3>
{
articles[i].content.map(paragraph =>
(<p dangerouslySetInnerHTML={{ __html: paragraph }} />)
)
}
</div>
);
}
Here's a working example as well - hope that helps!

JavaScript - Replace a string with anchor tag while fetching data from JSON Array

I have encountered this problem while doing loop over array of objects. Consider I have below array of objects.
General : [
{
question: 'Whats you suggestion?',
answer: "Before you go ahead and book one of our trusted developer, please read our FAQ.",
},
{
question: 'Do you have guaranteed solution?',
answer: 'Please let us know at hello#stackoverflow.com.',
}
]
I am using map in my JSX (react application) something like this.
General.map((faq, index) => (
<details>
<summary>{faq.question}</summary>
<div>
<Linkify>{faq.answer}</Linkify>
</div>
</details>
))}
Now I want the text hello#stackoverflow.com to render as html anchor tag. I have done this through React Linkify. But how we can achieve this with pure javascript ?
This will work for emails, but you'll need to work out the regex for urls and chain them. Hope it helps.
General.map((faq, index) => {
const emailRegex = /([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/g;
const emailReplacer = "<a href='mailto:$1'>$1</a>";
return (
<details>
<summary>{faq.question}</summary>
<div>
<div>
{faq.answer.replace(emailRegex, emailReplacer)}
</div>
</div>
</details>
)
})

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings
'No results' and 'Please try another search term.'.
I have tried 'No results.<br>Please try another search term.'
but it does not work, I need to add the <br> in the html.
Any ideas how to solve it?
render() {
let data = this.props.data;
let isLoading = this.props.isLoading;
let isDataEmpty = Object.entries(data).length === 0;
let movieList = isLoading ? <Loader /> : isDataEmpty ? 'No results. Please try another search term.' :
Object.entries(data).map((movie, index) => <MovieTile key={index} {...movie[1]} />);
return (
<div className='movieList'>{movieList}</div>
);
}
You should use JSX instead of string:
<div>No results.<br />Please try another search term.</div>
Because each jsx should have 1 wrapper I added a <div> wrapper for the string.
Here it is in your code:
render() {
let data = this.props.data;
let isLoading = this.props.isLoading;
let isDataEmpty = Object.entries(data).length === 0;
let movieList = isLoading ? <Loader /> : isDataEmpty ? <div>No results.<br />Please try another search term.</div> :
Object.entries(data).map((movie, index) => <MovieTile key={index} {...movie[1]} />);
return (
<div className='movieList'>{movieList}</div>
);
}
You can use CSS white-space to solve the problem.
React Component
render() {
message = `No results. \n Please try another search term.`;
return (
<div className='new-line'>{message}</div>
);
}
CSS
.new-line {
white-space: pre-line;
}
OUTPUT
No results.
Please try another search term.
break text to line:
render() {
...
<div>
{this.props.data.split('\n').map( (it, i) => <div key={'x'+i}>{it}</div> )}
</div>
...
Some HTML elements such as <img> and <input> use only one tag. Such tags that belong to a single-tag element aren't an opening tag nor a closing tag. Those are self-closing tags.
In JSX, one has to include the slash. So, remove <br> and try <br />
Here is how I got around this. Let message be the prop/variable that has the string containing line breaks to be displayed in HTML as follows:
message = 'No results.<br>Please try another search term.';
<div>
{message}
</div>
To make this work, we need to use \n instead of break tag <br> and set the following css on the wrapper element of this message as follows:
message = 'No results.\nPlease try another search term.';
<div className="msg-wrapper">
{message}
</div>
CSS:
.msg-wrapper {
white-space: pre-wrap;
}
OUTPUT:
No results.
Please try another search term.
If you don't want put the string inside a <div> you could use <> to do it.
Like this:
var text = <>This is a text in the first line;<br />this is a text in a second line</>;
Just split text by /n, I do this in this way:
<div>
{text.split('\n').map((item, i) => <p key={i}>{item}</p>)}
</div>
Try with span
return (
<div className='movieList'><span>{movieList}</span></div>
);
If you are like in my situation and you don't want to add css, you can do that :
render () {
...
return (
...
<Typography component="p">
...
{(contact.lastname)?<div>Hello {contact.firstname} {contact.lastname}</div>:''}
...
</Typography>
...
);
}
using ` worked for me however i am not sure if it is the exact solution to the problem :
import React from 'react';
import ReactDOM from 'react-dom';
let element = (
<div>
<h1> Hello world</h1>
This is just a sentence <br></br>
But This line should not be in the same previous line. <br></br>
The above content proves its working. <br></br>
npm v6.14.6 | react : {React.version}
</div>
);
ReactDOM.render(element,document.getElementById("html-element-id"))
You can add a span tag and add block as a class.
Pomodoro Technique Timer <span className="block">with Bla</span>
The simplest thing which I did is by creating a component.
const EmptySpace = ({ spaceCount = 0 }) => {
return (
<>
{Array.from({ length: spaceCount }, (item, index) => {
return <br key={index} />;
})}
</>
);
};
export default EmptySpace;
<EmptySpace spaceCount={1} />
In your case you could do something like this:
const msg = (
<p>
No results <EmptySpace spaceCount={2} />
Please try another search term.
</p>
);

Categories

Resources