'Concat string with html element in react
This might give a better idea, replace in paragraph, ' ==> " and highlight it
for (let i=0; i<orgString.length;i++) {
changeVal.push("color:#" + Math.floor(Math.random() * 16777216).toString(16))
let spanStart = <span style={changeVal[i]}> '"' </span>
if (orgString.charAt[i] === "'") {
let newSubstring = orgString.substring(0,orgString.charAt[i]);
orgString = newSubstring + spanStart + orgString.substring(orgString.charAt[i+1], orgString.length);
}
}
Trying to change the multiple values, so concatenating in same string and render it once entire string is iterated
But getting output with [object Object] where concatenated HTML element
Solution 1:[1]
If the dynamic string to be concatenated is composed of text, use brackets inside of JSX:
const Snippet = () => {
str = 'The world is new'
return (<>
{str}
<p style={{ color: 'blue' }}>Every Morning</p>
</>);
}
(also note that JSX elements styles' must be set with syntax like style={{ styleProp: stylePropVal }}
, and you need to assign the function to a variable; const () => {
will throw a syntax error)
Otherwise, you'll have to use dangerouslySetInnerHTML
:
const Snippet = () => {
const str = 'The world <b>is new</b>'
return (<React.Fragment>
<div dangerouslySetInnerHTML={{ __html: str }} />
<p style={{ color: 'blue' }}> Every Morning</p>
</React.Fragment>);
};
ReactDOM.render(<Snippet />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
But it'd be better to avoid that if at all possible - use text, state and JSX elements instead whenever you can.
Solution 2:[2]
Simply Use React.Fragment:
const data = () => {
str = 'The world is new'
para = str + <p style='color:blue'> Every Morning</p>
return (
<React.Fragment>
{para}
</React.Fragment>
);
}
or
const data = () => {
str = 'The world is new'
para = str + <p style='color:blue'> Every Morning</p>
return (
<>
{para}
</>
);
}
Solution 3:[3]
I used this combination when mixing HTML tags with javascript variables
<li className="row"><strong> Alerts: </strong> <br/> {`${user.alerts}`} </li>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Birender Pathania |
Solution 3 | Enrique Cuchetti |