-1

I have an array of html elements, lets say messages. And i want to render them as follow:

this.state.messages.push('<span className={Styles.success-message}>User successfully added</span>');

And in render method:

     {this.state.messages.map((value, index) => {
         return <div key={index}>{value}</div>
     })}

But during my rendering instead of getting the message with appropriate style i m getting the entire element as string: enter image description here

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
pikk
  • 837
  • 5
  • 21
  • 38
  • Does this answer your question? [Rendering raw html with reactjs](https://stackoverflow.com/questions/27934238/rendering-raw-html-with-reactjs) – Emile Bergeron Mar 17 '20 at 15:54
  • You should avoid raw HTML strings whenever possible and instead manage data that can be rendered with JSX to fully benefit from React. – Emile Bergeron Mar 17 '20 at 15:55

3 Answers3

1

if you have html tags in state array you can use like this-

class App extends React.Component {
  state = {
    messages: [
      `<span>User successfully added</span>`,
      `<span>User successfully removed</span>`
    ]
  };
  render() {
    return (
      <>
        {this.state.messages.map((item,index) => (
          <h3 key={index} dangerouslySetInnerHTML={{ __html: item }} />
        ))}
      </>
    );
  }
}

Live working demo https://codesandbox.io/s/quizzical-leftpad-p3hib

akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
0

Do it using dangerouslySetInnerHTML feature from React. There is an example in the below link.

https://reactjs.org/docs/dom-elements.html

Nayan shah
  • 543
  • 3
  • 8
-1

First of all, you should never mutate state , which is ground rule of react.

Coming to issue, you're pushing a string , instead what you should be doing is

let messages =  [];
messages.push(<span className={Styles.success-message}>User successfully added</span>)
this.setState({ messages })

and then loop through this array in render() method like

this.state.message.map((value, messageIndex) => <div key={messageIndex} > {value} </div>)

vamshi krishna
  • 2,618
  • 1
  • 11
  • 18