'ReactJS how to render an HTML object span element within a string
How can I convert an HTML object containing a span element within a string into something that Reactjs can actually render as HTML?
To clarify, here's what I have:
let myObject = "apple tree"
I wrote a function that wraps the word apple in a span tag (html object)
<span style="color: red;">apple</span>tree
my website is displaying:
[object Object] tree
BUT it should be displaying
apple tree
where "apple" is colored red because it is wrapped in a span
I'm passing the string into my component like this:
return (<div>{myObject}</div>)
Not sure how to render this object as actual HTML element, and not sure if I doing dangerouslySetInnerHTML is the best and only option here too
Solution 1:[1]
How about this?
{<span style="color: red;">{'apple'}</span>tree}
Lemme know if it works.
Solution 2:[2]
If you want to render an HTML object it's just
let myObject=<span style="color: red;">apple</span>;
return (<div>{myObject} tree</div>);
if you are doing something like this return (<div>{this.getRedApple()} tree</div>);
then in your getRedApple()
function you should just return the variable like so:
let myObject=<span style="color: red;">apple</span>;
return (myObject);
Don't have it like this: return ({myObject})
Solution 3:[3]
Create component for it
class Apple extends Component {
render() {
return <span color={this.props.style.color} >{this.props.strApple}</span>tree;
}
}
use that component;
const style = { color: 'red' };
const element = <Apple strApple="apple tree" style="style "/>;
And render it
ReactDOM.render(
element,
document.getElementById('root')
);
Solution 4:[4]
This Question is already answered here. Insert value of object into span tag
Referring to answer of Nitin Dhomse, you can do something like this:
let myObject = "apple tree";
<span id="span" style="color: red"></span>
$("#span").text(myObject);
This will give you the required output.
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 | Nevin Madhukar K |
Solution 2 | Jayce444 |
Solution 3 | |
Solution 4 |