Is there any way to pass HTML
entities as function parameters in JavaScript.
I am building a React app and I need to pass HTML
entities from parent component to child component as a prop
and then display character represented by that entity in the child component.
For example, please refer stackblitz here.
In Hello
component I need to print htmlEntity
received from App component as a prop
and display character represented by that entity, in this case it would be symbol – ”.
How this can be achieved?
Advertisement
Answer
one way is to use dangerouslySetInnerHTML
in react.
JavaScript
x
11
11
1
function createMarkup(str) {
2
return {__html: str};
3
}
4
5
function MyComponent({str}) {
6
return <div dangerouslySetInnerHTML={createMarkup(str)} />;
7
}
8
9
const myText = 'First · Second';
10
<MyComponent str={myText} />}
11
another way is to use Unicode characters with escape notation (e.g. u0057) instead of HTML codes (·).
JavaScript
1
7
1
function MyComponent({str}) {
2
return <div>{str}</div>;
3
}
4
5
const myText = 'First u0057 Second';
6
<MyComponent str={myText} />
7