React - dangerouslySetInnerHTML being displayed as plain text - javascript

I've created a React app that displays job postings. When I click on a job post in the list, that particular job post's details are displayed.
I'm trying to display the body of the job post in the same way that it has been formatted at the source. To do that, I've tried using the following code:
<div id="apply-now" className="apply-section">
<h3>How to apply.</h3>
<div dangerouslySetInnerHTML={{ __html: currentJob.description }}></div>
</div>
However, when the component is rendered, the content is not formatted and is displayed in plain text without the appropriate formatting.
Here's an example that hasn't been formatted:
The word __"Application"__ should be in bold, the website link should be an actual link, as should "Click here for an application form" link.
The data I'm getting back from the API call is the same as above:
Join us! - We are looking forward to your application via the "Application" form Your contact: Ralph Ullmann Telefon: 089/ 5511 333783 https://www.consorsfinanz.de/karrier Click here for the application form!"
^^ Even above on StackOverflow it works! But I can't get it to work in my app!
I've been tearing my hair out for hours trying to fix this and I can't even understand why it doesn't work.

This sounds like an algorithm challenge. Sorry thought it could be done in an elegant way, but regex would be the better option
Use regex to match anything inbetween two underscores
In each match, replace remove the underscores and wrap each element in strong tags
const mdBoldToStrong = (text) => {
const surroundingUnderscores = new RegExp(/__(.*?)__/g)
return text
.replace(surroundingUnderscores, (word) => {
return `<strong>${word.replace(/__/g, '')}</strong>`
})
}
console.log(mdBoldToStrong('__Application__'))
console.log(mdBoldToStrong('Text__Application__Text__'))
console.log(mdBoldToStrong('__Text____Application__Text'))
Please let me know if you need any clarification.

Related

Replacing new line with <br> tag express javascript

I am creating a blog website.I am taking the input using a text area and storing it in the mongodb.Before storing the data in mongodb I perform the following function:
req.body.content=req.body.content.replace(/\n/g ,"<br>");
I saw this on another stackoverflow post.
Now the problem is for the first time \n is replaced with . Now if I edit the post then the above function is executed again so the tag is added again to the unmodified text(which I don't want to happen).
Ex:
First time:
hello
javascript
world
is replaced as
hellojavascriptworld.
Second time(when I edit it):
hello
javascript
express
world
is replaced as
hellojavascriptexpressworld.
Please help me.Thanks in advance.
Don't modify user input. Instead, use CSS to format text, e.g.
p { white-space: pre }

Wrap text in a Vue component dynamically

Problem
I want to wrap some plain text in a Vue component dynamically, using mouseUp after selecting the text.
For example: <div> Hello World! </div> => <div> <Greeting/> World! </div>
Aprox solution
Right now, I'm wrapping it using document.createElement("span") and surrounding the range of the selection with it.
I have found similar questions like the next one, but I'm trying to avoid render level:
How can I dynamically wrap a substring with a component in Vue.js?
Well, I finally managed to solve it. (Before submitting, I spend a lot of time figuring out. I don't know how I solved it so fast)
Solution
var ComponentClass = Vue.extend(Annotation);
var instance = new ComponentClass();
instance.$mount();
this.range.deleteContents();
this.range.insertNode(instance.$el);
Where: Annotation is a Vue component and the Range is the selection range obtained previously.
I hope this help someone else!

Display article from backend and style it with html

I have backend that is returning me whole article body text as String. On my website I want to create each article in different HTML/CSS style, for example have <br> tag to break article when it is too long. But some articles will not be long, so I can't place <br> tag inside my frontend component.
As my frontend component is not changing based on size of this text, I came up with an idea to store <br> tags directly inside article String texts. But data is coming as a string with <br> tags in it, the tags are treated also as a string, so it has no effect on styling.
Should I somehow escape these tags from string? Or is there a better way to do it? I don't have idea how it should be done properly.
If you are receiving raw html content that already has markup tags within it that you want to render in ReactJS, then you need to use React's dangerouslySetInnerHTML attribute. Depending on where you are holding the markup you received from the backend, your code somewhere within your Render function would look something like this:
<div dangerouslySetInnerHTML={this.state.recievedArticleRawText} />
see official documentation here for caveats and warnings on usage: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
Essentially, the React team purposefully chose to name this dangerously because you should only use it if you 100% fully trust the value you are setting. Do not ever set values input by the user to this attribute because it leaves holes for all kinds of injection.
If you use innerHTML, then it should work correctly - given that you don't use < br >, as that's not a valid HTML entity (<br /> and <br> are).
const text1 = '1. This is a line< br >This should be the next line.'
const text2 = '2. This is a line<br>This should be the next line.'
const text3 = '3. This is a line<br />This should be the next line.'
document.getElementById('text1').innerHTML = text1 // expected to not work correctly
document.getElementById('text2').innerHTML = text2 // expected to work correctly
document.getElementById('text3').innerHTML = text3 // expected to work correctly
<span id="text1"></span>
<hr />
<span id="text2"></span>
<hr />
<span id="text3"></span>

How to replace html tags with our own tags

In my MVC web application, I have a text area inside View, in that user will put HTML text so in that text, I want to replace html tags with my own custom tags.
For Example:
HTML tag:
<input type='text' name='MyList.First_Name' data-val='true' data-val-required='Please enter first name' />
Replace with:
[~TextFieldTag|MyList.First_Name|||0|data-val=>true|data-val-required=>Please enter first name|~]
Can anyone suggest what is the best approach to do this?
I was going to recommend a simple string replacement at first, but given the seemingly complicated nature of your replacements, that might not be the best approach.
Probably the best approach would be to take the HTML, convert it to DOM elements, which can be done simply by throwing it into an elements innerHTML:
document.querySelector('button').addEventListener('click', () => {
document.querySelector('#renderSpace').innerHTML = document.querySelector('textarea').value;
});
Add some HTML:
<textarea></textarea>
<button>Press Me</button>
<div id="renderSpace"></div>
You can position the area you render it inside of off-screen so users don't actually see it.
From there, I would walk the DOM tree (basically, start at the root, then look at all of its children, then their children, etc., recursively), reading off any properties that you deem appropriate and then writing your string replacement as you go along.
That does require that they have entered valid HTML (which is generally a requirement, but can be difficult to rely on users to enter), so you'll want to have some good, user-friendly, error handling in there.

String with new line and tabs to display in HTML

I have a string coming from my java backend which is formatted to display in a certain way, the new line, tab and space characters are in certain positions.
How do I get this to display the same way in HTML?
For example, say I have the current string in Javascript as so:
var str = "\t\tTitle \n Some text \t\t\t more text";
Browsers typically strip out extra white space, you might need to put it inside a preformatted text block or use white-space: pre
var pre = document.createElement("pre");
pre.innerHTML = str;
document.appendChild(pre);
Also yes, you need to use backslahes too, as mentioned about.
I might be late but just in order to help if a beginner like me is facing this kind of problem.
You can add a css class to the html tag where you want to display the data. In my case I am using ngFor of Angular 2. The data coming from my back end had line breaks and tabs. So I just added a class to the html tag with a css white-spacing style as follows.
Backend Data"title": "postIssueResponse() {\n\tthis.parent.postIssueResponse(this.issueId, this.newResponse);\n console.log(this.newResponse);\n this.newResponse \u003d \"\";\n}"
<p class="response-title">{{myData?.title}}</p>
And the css
.response-title {
white-space:pre;
}
This one do the job perfectly.
You can use textarea also. here is a Working Fiddle
MDN textarea

Categories