How to force a line break from string content? - javascript

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.

Related

literal string with div tag

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.

rendering an array of strings and add between each element a new line - ReactJS

What I'm trying to do is in the return of a render method, to add a newline between each element of an array (of strings).
I've tried two ways (one of them is commented):
import React, { Component } from 'react'
export default class extends Component {
render() {
return (
<div>
<div>
<div className='Dog'>
{this.props.name}
<p>Age: {this.props.age}</p>
{/* <text>About: {this.props.fact.map((f) => f+'\n')}</text> */}
<p>{this.props.fact.join('\n')}</p>
</div>
</div>
</div>
)
}
}
The result is not what I was looking for:
image #1 - result without any of my attempts (as if - just rendering {this.props.fact}:
image #2 - with my attempt (both attempts end up with same result):
AAAAAAAAAAAH, I'm clueless!
Thanks in advance.
Since whitespace is largely ignored, outputting a newline (\n) won't actually insert a line break. Instead, just use the line break tag (<br>).
In JSX, that looks like <br />. Since you need to return a single element, you'll also want wrap your text and line break in a fragment (<>...</>):
<text>
About:{" "}
{this.props.fact.map((f) => (
<>
{f}
<br />
</>
))}
</text>
If it's just text, you could use dangerouslySetInnerHTML
<p dangerouslySetInnerHTML={{ __html: this.props.fact.join('\n') }} />

Getting incorrect output when I try to render HTML in react

I am currently developing a chat application. In the application i am taking input using ReactQuill wysiwyg editor.
I am taking input from the editor which is a string that has html for example :
Output-> I want to render the output again in html to a chatbox inside a 'div'.
My research ->
We can use dangerouslySetInnerHTML to render the html.
We can use a library called react-highlight
We can use parse function from "html-react-parser" library eg : parse(html)
I have tried all the above methods but i am getting this same output for all the above methods.
I would like to get the exact output which i wrote in the editor but as you can see the numbered list is not showing and only plain text is being shown.
I am new to web development so please excuse me if I made some error or I asked the question in a wrong way.I have also attached the code snippet of the application below
import React from "react";
const Message = (props) => {
function CreateElement() {
return <div dangerouslySetInnerHTML={{ __html: props.msg.text }}></div>;
}
return (
<div
id={props.msg.idx}
className={`flex ${
props.user.toLowerCase() !== props.msg.user
? "justify-start"
: "justify-end"
}`}
>
<div
class={`relative max-w-xl px-4 py-2 ${
props.user.toLowerCase() !== props.msg.user
? "bg-gray-700 text-white border-2 border-gray-400"
: "text-gray-700 border-2 border-gray-800"
} rounded shadow-md `}
>
{CreateElement()}
</div>
</div>
);
};
export default Message;
EDIT 1:
HTML STRUCTURE:

replace string text with html tag using regex

I've this text in string:
let text = "#Jim, Start editing to see some magic happen!";
how can I want to make it to?
text = "<span style="color:red">#Jim</span>, Start editing to see some magic happen!";
my failed attempt as below:
export default function App() {
let text = "#Jim, Start editing to see some magic happen!";
// const regex = /#|\[|\]/gm;
// text = text.replace(regex, (innerText) => {
// return <span style={{ color: "red" }}>{innerText}</span>;
// });
return (
<div className="App">
<div
dangerouslySetInnerHTML={{
__html: text
}}
/>
</div>
);
}
https://codesandbox.io/s/youthful-gwen-55757z?file=/src/App.js:24-419
I'm not sure this is what you really need. Anyway, I think it's a step closer.
I made a new regex to get '#' + words and for the text to be updated with replace it is necessary to play
text = text
Then:
import "./styles.css";
export default function App() {
let text = "#Jim, Start editing to see some magic happen!";
const regex = /\#[a-zA-Z]+/gm;
text = text.replace(regex, (match) => {
return `<span style="color: red">${match}</span>`;
});
return (
<div className="App">
<div
dangerouslySetInnerHTML={{
__html: text
}}
/>
</div>
);
}
Your approach works, its just that the style is not rendered in innerHTML
Run this example and you'll see that the hashtag appears bold (Also changed your regex a bit)
let text = '#Jim, Start editing to see some magic happen!';
const regex = /(#+[a-zA-Z0-9(_)]{1,})/gm;
text = text.replace(regex, (match) => {
return `<strong>${match}</strong>`;
});
If you want the styles to apply you have to change the Encapsulation in your component to None like so:
#Component({
selector: 'app-my-hashtag-component',
styles: ['./app-my-hashtag-component.css'],
templateUrl: './app-my-hashtag-component.html',
encapsulation: ViewEncapsulation.None,
})

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