Skip to content Skip to sidebar Skip to footer

Avoid Using Dangerouslysetinnerhtml When Wrapping Html In React.js

I have this functionality for highlighting certain characters in the HTML of my component: highlightQuery() { // will output the text response from the Model, but also highligh

Solution 1:

I'm not sure this will perfectly answer your question but I would do this to avoid dangerouslySetInnerHTML.

render() {

      highlightQuery() {

        let input = this.props.model.get('value');

        if(!this.state.hasMatch){
            return input;
        }

        let query = this.props.matched.query,
            index = this.props.model.get('searchIndexes')[this.props.matched.index];

        constreplaceBetween = (str, start, end, what) => {
        return str.substring(0, start) + what + str.substring(start + end);
        };

        let ret = replaceBetween(input, index, query.length, `<span class='highlighted'>${query}</span>`);

        return ret;
    }

    var mycontent = highlightQuery();

    return (
        <span> {mycontent} </span>
    );

}

hope it helps

Edit: I think I understand what you've meant now but in my opinion it doens't change the strategy, you work inside the render, choose your content and render it. (or maybe I still don't get it.. =p)

Solution 2:

Is there any reason highlightQuery cannot return a react element?

highlightQuery(input,query, index) {
    // will output the text response from the Model, but also highlight relevant words if they match the search query// that the user inputvar before = input.substring(0, index);
    var after  = input.substring(index + query.length);
    return<span>{before}<spanclass='highlighted'>{query}</span>{after}</span>;
},

render() {
    var input = this.props.model.get('value');
    var query = this.props.matched.query;
    var index = this.props.model.get('searchIndexes')[this.props.matched.index];

    if(!this.state.hasMatch){
        return<span>{input}</span>;
    } else {
        returnhighlightQuery(input, query, index);
    }

}

Post a Comment for "Avoid Using Dangerouslysetinnerhtml When Wrapping Html In React.js"