0

New to React here, I have an input that is live updating text displayed below it. I want to click the user to click a button and wrap each word that has been typed with an html span or div tag. I can get it to output all as a string but I need it to be interpreted as html.

    class App extends Component {
    constructor(props) {
        super(props);

        this.state = { message: '' };

    }

    onChange(e) {
        this.setState({message: e.target.value});
    }

    onClick(e) {
        var text = this.state.message.split(" ");
        console.log(text);
        var newText = "";
        text.forEach(function(element) {
            newText += "<div>" + element + "</div>";
        });
        this.setState({message: newText});
    }


    render() {

        return (
            <div> 
                <InputBar onChange={this.onChange.bind(this)} value={this.state.message}/>
                <UpdateCss onClick={this.onClick.bind(this)} />
                <Output message={this.state.message} />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.querySelector('.container'));

So currently it outputs as something like <div>this</div><div>is</div><div>a</div><div>string</div>. Is there an easier way to do this that I am not seeing?

azium
  • 20,056
  • 7
  • 57
  • 79
Brian Edelman
  • 727
  • 4
  • 10
  • 26
  • Binding functions should be put inside of the constructor, like this: this.onChange = this.onChange.bind(this); See http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html for more info. – Chad Dec 22 '16 at 19:42
  • Check the accepted answer here: http://stackoverflow.com/questions/19266197/reactjs-convert-to-html **Be vary of XSS vulnerabilities.** – Nikolaj Dam Larsen Dec 22 '16 at 21:00

1 Answers1

0

Try using dangerouslySetInnerHTML this is the way that Reactjs renders HTML passed as strings. https://facebook.github.io/react/docs/dom-elements.html#dangerouslysetinnerhtml