Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding html tag inside javascript string

I have the following code in react js:

'use strict';

module.exports = {
    homePage: {
        sliderTitle: 'Creative portfolio',

        loginTitle: 'Do you already <b>have</b> an account?'

    },
    registrationPage: {
        foo: 'bar'
    }
};

When I try to use those labels I have

var EN = require('./en');
{EN.homePage.loginTitle}

but {EN.homePage.loginTitle} returns the string with b tags inside.

How can I apply this b tag to the word have?

like image 432
Boky Avatar asked Jan 06 '23 01:01

Boky


1 Answers

One option as mentioned in the comments is to use dangerouslySetInnerHTML assigning loginTitle a __html object (note the double underscore '__') and passing it to the element as a prop.

loginTitle: {__html: 'Do you already <b> have </b> an account?' }
...
<div dangerouslySetInnerHTML={EN.homePage.loginTitle}></div>

Generally speaking though you should avoid using dangerouslySetInnerHTML whenever possible as emphasized in the docs: https://facebook.github.io/react/tips/dangerously-set-inner-html.html

There are other safer options to insert HTML in your text outlined here: http://facebook.github.io/react/docs/jsx-gotchas.html

One that should work well for you in this situation is to used a mixed array of strings & JSX, so:

loginTitle: ['Do you already ', <b>have</b>, ' an account']
...
<p>{EN.homePage.loginTitle}</p>

Here's a DEMO as well just to illustrate that both approaches have the same effect.

like image 81
Brad Colthurst Avatar answered Jan 08 '23 14:01

Brad Colthurst