3

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

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
user3226932
  • 2,042
  • 6
  • 39
  • 76

4 Answers4

0

How about this?

{<span style="color: red;">{'apple'}</span>tree}

Lemme know if it works.

Nevin Madhukar K
  • 3,031
  • 2
  • 25
  • 52
0

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})

Jayce444
  • 8,725
  • 3
  • 27
  • 43
0

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')
);
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
0

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.

  • 1
    Probably want to use a React specific solution for a question with a `reactjs` tag. jQuery and React aren't really designed to play together. Sure, there's [instructions on adding a jQuery plugin to a React app](https://reactjs.org/docs/integrating-with-other-libraries.html#how-to-approach-the-problem), but those gymnastics aren't required here imo. – ruffin Dec 27 '22 at 17:16