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 ponent 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
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 ponent 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
Share Improve this question edited Mar 15, 2017 at 6:32 RIYAJ KHAN 15.3k5 gold badges33 silver badges55 bronze badges asked Mar 15, 2017 at 6:20 user3226932user3226932 2,25211 gold badges53 silver badges87 bronze badges4 Answers
Reset to default 0If 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})
Create ponent for it
class Apple extends Component {
render() {
return <span color={this.props.style.color} >{this.props.strApple}</span>tree;
}
}
use that ponent;
const style = { color: 'red' };
const element = <Apple strApple="apple tree" style="style "/>;
And render it
ReactDOM.render(
element,
document.getElementById('root')
);
How about this?
{<span style="color: red;">{'apple'}</span>tree}
Lemme know if it works.
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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745182148a4615468.html
评论列表(0条)