I have array of names. I want to make bold for first name. It is not always for only index=0. I have different case where later the second name might need to be bold. I am trying to convert html code to string. But, when I try to print it on screen, I just get {names[0]} with b tags.
const names=["First", "second", "third"];
names[0] = `<b>{names[0]}</b>`;
return names.map(name=><span>{name}</span>);
CodePudding user response:
React by default escapes all strings to prevent XSS attacks.
dangerouslySetInnerHTML
is really dangerous and shouldn't be used if name comes from user input.
Easy solution is wrap the first item by <b>
JSX tag
const names = ["First", "second", "third"];
return names.map((name, index) => (
<span>{index === 0 ? <b>{name}</b> : name}</span>
));
CodePudding user response:
You have to use dangerouslySetInnerHTML
, otherwise it will be just seen as mere text.
You can read more about this React attribute in the docs: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml.
An example is:
function createMarkup() {
const names=["First", "second", "third"];
names[0] = `<b>{names[0]}</b>`;
return {__html: names.map(name=><span>{name}</span>)};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
Where in createMarkup
you write in the stuff you had and then render it as shown in myComponent
.
CodePudding user response:
Trying to convert HTML to string is not the best way to go about this. Here is a better way to achieve this:
return (
<div>
{names.map((name, i) => (
<span style={{ fontWeight: i === 0 ? "bold" : "normal" }}>{name}</span>
))}
</div>
);
i
is the index of the array element in the map
loop. This will make the text bold only if i === 0