javascript - React search highlighing -


i trying make search highlights matching characters within displayed list.

i having trouble figuring out how can add dom node within list being created/updated. following code got to. think understand why not working (i keep getting 'stephine ma[object object]ks'as output). sure need add actual dom node using .html or .innerhtml react im not sure how 1 that.

import react 'react'; import { router, route, link } 'react-router';  export default class extends react.component {      constructor(props) {         super(props);         this.state = {};     }      render() {         var divimage = {             backgroundimage : "url(" + this.props.image + ")"         };         var test = this.props.name;          if(this.props.name.indexof(this.props.filtertext) != -1 ) {             var pattern = this.props.filtertext.tostring();             test = test.replace(pattern, <span classname="highlight">+pattern+</span>)         }         return (             <li classname="panelitem">                 <a classname="item-title" style={divimage}>{test}</a>             </li>         );     } } 

here example if can use indexof instead of regex matching. builds nodes , wraps them in spans.

https://jsfiddle.net/2zx84koy/

var hello = react.createclass({     render: function() {          var name = this.props.name;         var startidx = name.indexof(this.props.filtertext);         var textnodes = <span>{name}</span>          if(startidx > -1 ) {           textnodes = (             <span>                 {name.substring(0, startidx)}                 <span classname="highlight">{name.substring(startidx, startidx + this.props.filtertext.length)}</span>                 {name.substring(startidx + this.props.filtertext.length)}             </span>            )         }           return (             <li classname="panelitem">                 <a classname="item-title">{textnodes}</a>             </li>         );     } }); 

you can innerhtml in react in general not advised unless know sure not leave vulnerable xss attacks. put example below of how convert code style reference.

var test = this.props.name;  if(this.props.name.indexof(this.props.filtertext) != -1 ) {     var pattern = this.props.filtertext.tostring();     test = test.replace(pattern, '<span class="highlight">' + pattern + '</span>') }   return (     <li classname="panelitem">         <a classname="item-title" dangerouslysetinnerhtml={{__html: test}}></a>     </li> ); 

Comments