How to apply highlighting match characters within the autosuggestion list in Reactjs?












0















I'm building a search engine, and want to change the color of matching characters



I'm using regex to matching an input value with array items, I've searched about solving a highlighting issue and I found this: item.replace(regex, '<mark>$1</mark>') but I don't know how to implement it.



  onTextChange = (e) => {
const value = e.target.value;
let suggestions = ;
if(value.length > 0) {

const regex = new RegExp(`${value}`, 'i');
suggestions = this.items.sort().filter(v => regex.test(v));

this.setState(() => ({ suggestions, textValue: value }));
}
this.setState(() => ({ suggestions, textValue: value }));

}

//this function return autosuggestion list

renderSuggestions () {
const {suggestions} = this.state;
if(suggestions.length !== 0) {

//suggestionSelected() hidden suggestion list after clicking

return(
<div className="auto-suggestions">
<ul>
{suggestions.map((item) =>
<li key={item} className="suggestion-item" onClick={()=>
this.suggestionSelected(item)}>{item}</li>)}
</ul>
</div>
);
}
}

//within the render() I have:

const {suggestions, textValue} = this.state;
<div className="container">
<input type="text" onChange={this.onTextChange} value= {textValue} />
{this.renderSuggestions()}
{this.showUsers()}

</div>


I'm not sure where and how could solve this problem, any help would be appreciated.










share|improve this question



























    0















    I'm building a search engine, and want to change the color of matching characters



    I'm using regex to matching an input value with array items, I've searched about solving a highlighting issue and I found this: item.replace(regex, '<mark>$1</mark>') but I don't know how to implement it.



      onTextChange = (e) => {
    const value = e.target.value;
    let suggestions = ;
    if(value.length > 0) {

    const regex = new RegExp(`${value}`, 'i');
    suggestions = this.items.sort().filter(v => regex.test(v));

    this.setState(() => ({ suggestions, textValue: value }));
    }
    this.setState(() => ({ suggestions, textValue: value }));

    }

    //this function return autosuggestion list

    renderSuggestions () {
    const {suggestions} = this.state;
    if(suggestions.length !== 0) {

    //suggestionSelected() hidden suggestion list after clicking

    return(
    <div className="auto-suggestions">
    <ul>
    {suggestions.map((item) =>
    <li key={item} className="suggestion-item" onClick={()=>
    this.suggestionSelected(item)}>{item}</li>)}
    </ul>
    </div>
    );
    }
    }

    //within the render() I have:

    const {suggestions, textValue} = this.state;
    <div className="container">
    <input type="text" onChange={this.onTextChange} value= {textValue} />
    {this.renderSuggestions()}
    {this.showUsers()}

    </div>


    I'm not sure where and how could solve this problem, any help would be appreciated.










    share|improve this question

























      0












      0








      0








      I'm building a search engine, and want to change the color of matching characters



      I'm using regex to matching an input value with array items, I've searched about solving a highlighting issue and I found this: item.replace(regex, '<mark>$1</mark>') but I don't know how to implement it.



        onTextChange = (e) => {
      const value = e.target.value;
      let suggestions = ;
      if(value.length > 0) {

      const regex = new RegExp(`${value}`, 'i');
      suggestions = this.items.sort().filter(v => regex.test(v));

      this.setState(() => ({ suggestions, textValue: value }));
      }
      this.setState(() => ({ suggestions, textValue: value }));

      }

      //this function return autosuggestion list

      renderSuggestions () {
      const {suggestions} = this.state;
      if(suggestions.length !== 0) {

      //suggestionSelected() hidden suggestion list after clicking

      return(
      <div className="auto-suggestions">
      <ul>
      {suggestions.map((item) =>
      <li key={item} className="suggestion-item" onClick={()=>
      this.suggestionSelected(item)}>{item}</li>)}
      </ul>
      </div>
      );
      }
      }

      //within the render() I have:

      const {suggestions, textValue} = this.state;
      <div className="container">
      <input type="text" onChange={this.onTextChange} value= {textValue} />
      {this.renderSuggestions()}
      {this.showUsers()}

      </div>


      I'm not sure where and how could solve this problem, any help would be appreciated.










      share|improve this question














      I'm building a search engine, and want to change the color of matching characters



      I'm using regex to matching an input value with array items, I've searched about solving a highlighting issue and I found this: item.replace(regex, '<mark>$1</mark>') but I don't know how to implement it.



        onTextChange = (e) => {
      const value = e.target.value;
      let suggestions = ;
      if(value.length > 0) {

      const regex = new RegExp(`${value}`, 'i');
      suggestions = this.items.sort().filter(v => regex.test(v));

      this.setState(() => ({ suggestions, textValue: value }));
      }
      this.setState(() => ({ suggestions, textValue: value }));

      }

      //this function return autosuggestion list

      renderSuggestions () {
      const {suggestions} = this.state;
      if(suggestions.length !== 0) {

      //suggestionSelected() hidden suggestion list after clicking

      return(
      <div className="auto-suggestions">
      <ul>
      {suggestions.map((item) =>
      <li key={item} className="suggestion-item" onClick={()=>
      this.suggestionSelected(item)}>{item}</li>)}
      </ul>
      </div>
      );
      }
      }

      //within the render() I have:

      const {suggestions, textValue} = this.state;
      <div className="container">
      <input type="text" onChange={this.onTextChange} value= {textValue} />
      {this.renderSuggestions()}
      {this.showUsers()}

      </div>


      I'm not sure where and how could solve this problem, any help would be appreciated.







      javascript reactjs






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 2 at 3:32









      S.saadiS.saadi

      35




      35
























          2 Answers
          2






          active

          oldest

          votes


















          0














          You need to render the highlighted text in a plain html, you can have this sample



           safeHTML(item) {
          return item.replace(new RegExp(this.state.selectedText, 'gi'),'<strong>$&</strong>')
          }

          getHighlighted(item){
          return (
          <p key={item}
          dangerouslySetInnerHTML={{
          __html : this.safeHTML(item)
          }} />
          )
          }

          render() {
          return <div>
          {
          this.state.suggestions.map(s => {
          return this.getHighlighted(s)
          })
          }
          </div>;
          }


          PS: You need a sanitized data for security



          Hopefully this will help :)






          share|improve this answer
























          • it's a great way, it's work perfectly now. Thanks a lot

            – S.saadi
            Jan 2 at 9:44





















          0














          You have 2 problems to solve: (1) extract the matching substring in suggestions and (2) highlight the matching substring in your UI.



          You can use String.prototype.split instead of RegExp.prototype.test to split the string with matching regex and prepare necessary data for rendering:



          onTextChange = (e) => {
          const value = e.target.value;
          let suggestions = ;
          if(value.length > 0) {
          const regex = new RegExp(`${value}`, 'i');
          suggestions = this.items.sort().map(v => {
          const arr = v.split(regex);
          return arr.map(substr => ({
          value: substr,
          isMatched: regex.test(substr)
          }))
          });
          suggestions = suggestions.filter(arr => arr.some(({ isMatched}) => isMatched))

          this.setState(() => ({ suggestions, textValue: value }));
          }
          this.setState(() => ({ suggestions, textValue: value }));

          }


          then print out the suggestions list:



             renderSuggestions () {
          const {suggestions} = this.state;
          if(suggestions.length !== 0) {

          return(
          <div className="auto-suggestions">
          <ul>
          {suggestions.map((item) =>
          <li key={item} className="suggestion-item" onClick={()=>
          this.suggestionSelected(item)}>
          {item.map(({ value, isMatched}) =>
          {isMatched ?
          <span>{value}</span> :
          <strong>{value}</strong>
          }
          )}
          </li>)}
          </ul>
          </div>
          );
          }
          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000917%2fhow-to-apply-highlighting-match-characters-within-the-autosuggestion-list-in-rea%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            You need to render the highlighted text in a plain html, you can have this sample



             safeHTML(item) {
            return item.replace(new RegExp(this.state.selectedText, 'gi'),'<strong>$&</strong>')
            }

            getHighlighted(item){
            return (
            <p key={item}
            dangerouslySetInnerHTML={{
            __html : this.safeHTML(item)
            }} />
            )
            }

            render() {
            return <div>
            {
            this.state.suggestions.map(s => {
            return this.getHighlighted(s)
            })
            }
            </div>;
            }


            PS: You need a sanitized data for security



            Hopefully this will help :)






            share|improve this answer
























            • it's a great way, it's work perfectly now. Thanks a lot

              – S.saadi
              Jan 2 at 9:44


















            0














            You need to render the highlighted text in a plain html, you can have this sample



             safeHTML(item) {
            return item.replace(new RegExp(this.state.selectedText, 'gi'),'<strong>$&</strong>')
            }

            getHighlighted(item){
            return (
            <p key={item}
            dangerouslySetInnerHTML={{
            __html : this.safeHTML(item)
            }} />
            )
            }

            render() {
            return <div>
            {
            this.state.suggestions.map(s => {
            return this.getHighlighted(s)
            })
            }
            </div>;
            }


            PS: You need a sanitized data for security



            Hopefully this will help :)






            share|improve this answer
























            • it's a great way, it's work perfectly now. Thanks a lot

              – S.saadi
              Jan 2 at 9:44
















            0












            0








            0







            You need to render the highlighted text in a plain html, you can have this sample



             safeHTML(item) {
            return item.replace(new RegExp(this.state.selectedText, 'gi'),'<strong>$&</strong>')
            }

            getHighlighted(item){
            return (
            <p key={item}
            dangerouslySetInnerHTML={{
            __html : this.safeHTML(item)
            }} />
            )
            }

            render() {
            return <div>
            {
            this.state.suggestions.map(s => {
            return this.getHighlighted(s)
            })
            }
            </div>;
            }


            PS: You need a sanitized data for security



            Hopefully this will help :)






            share|improve this answer













            You need to render the highlighted text in a plain html, you can have this sample



             safeHTML(item) {
            return item.replace(new RegExp(this.state.selectedText, 'gi'),'<strong>$&</strong>')
            }

            getHighlighted(item){
            return (
            <p key={item}
            dangerouslySetInnerHTML={{
            __html : this.safeHTML(item)
            }} />
            )
            }

            render() {
            return <div>
            {
            this.state.suggestions.map(s => {
            return this.getHighlighted(s)
            })
            }
            </div>;
            }


            PS: You need a sanitized data for security



            Hopefully this will help :)







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 2 at 4:24









            SucSuc

            264




            264













            • it's a great way, it's work perfectly now. Thanks a lot

              – S.saadi
              Jan 2 at 9:44





















            • it's a great way, it's work perfectly now. Thanks a lot

              – S.saadi
              Jan 2 at 9:44



















            it's a great way, it's work perfectly now. Thanks a lot

            – S.saadi
            Jan 2 at 9:44







            it's a great way, it's work perfectly now. Thanks a lot

            – S.saadi
            Jan 2 at 9:44















            0














            You have 2 problems to solve: (1) extract the matching substring in suggestions and (2) highlight the matching substring in your UI.



            You can use String.prototype.split instead of RegExp.prototype.test to split the string with matching regex and prepare necessary data for rendering:



            onTextChange = (e) => {
            const value = e.target.value;
            let suggestions = ;
            if(value.length > 0) {
            const regex = new RegExp(`${value}`, 'i');
            suggestions = this.items.sort().map(v => {
            const arr = v.split(regex);
            return arr.map(substr => ({
            value: substr,
            isMatched: regex.test(substr)
            }))
            });
            suggestions = suggestions.filter(arr => arr.some(({ isMatched}) => isMatched))

            this.setState(() => ({ suggestions, textValue: value }));
            }
            this.setState(() => ({ suggestions, textValue: value }));

            }


            then print out the suggestions list:



               renderSuggestions () {
            const {suggestions} = this.state;
            if(suggestions.length !== 0) {

            return(
            <div className="auto-suggestions">
            <ul>
            {suggestions.map((item) =>
            <li key={item} className="suggestion-item" onClick={()=>
            this.suggestionSelected(item)}>
            {item.map(({ value, isMatched}) =>
            {isMatched ?
            <span>{value}</span> :
            <strong>{value}</strong>
            }
            )}
            </li>)}
            </ul>
            </div>
            );
            }
            }





            share|improve this answer




























              0














              You have 2 problems to solve: (1) extract the matching substring in suggestions and (2) highlight the matching substring in your UI.



              You can use String.prototype.split instead of RegExp.prototype.test to split the string with matching regex and prepare necessary data for rendering:



              onTextChange = (e) => {
              const value = e.target.value;
              let suggestions = ;
              if(value.length > 0) {
              const regex = new RegExp(`${value}`, 'i');
              suggestions = this.items.sort().map(v => {
              const arr = v.split(regex);
              return arr.map(substr => ({
              value: substr,
              isMatched: regex.test(substr)
              }))
              });
              suggestions = suggestions.filter(arr => arr.some(({ isMatched}) => isMatched))

              this.setState(() => ({ suggestions, textValue: value }));
              }
              this.setState(() => ({ suggestions, textValue: value }));

              }


              then print out the suggestions list:



                 renderSuggestions () {
              const {suggestions} = this.state;
              if(suggestions.length !== 0) {

              return(
              <div className="auto-suggestions">
              <ul>
              {suggestions.map((item) =>
              <li key={item} className="suggestion-item" onClick={()=>
              this.suggestionSelected(item)}>
              {item.map(({ value, isMatched}) =>
              {isMatched ?
              <span>{value}</span> :
              <strong>{value}</strong>
              }
              )}
              </li>)}
              </ul>
              </div>
              );
              }
              }





              share|improve this answer


























                0












                0








                0







                You have 2 problems to solve: (1) extract the matching substring in suggestions and (2) highlight the matching substring in your UI.



                You can use String.prototype.split instead of RegExp.prototype.test to split the string with matching regex and prepare necessary data for rendering:



                onTextChange = (e) => {
                const value = e.target.value;
                let suggestions = ;
                if(value.length > 0) {
                const regex = new RegExp(`${value}`, 'i');
                suggestions = this.items.sort().map(v => {
                const arr = v.split(regex);
                return arr.map(substr => ({
                value: substr,
                isMatched: regex.test(substr)
                }))
                });
                suggestions = suggestions.filter(arr => arr.some(({ isMatched}) => isMatched))

                this.setState(() => ({ suggestions, textValue: value }));
                }
                this.setState(() => ({ suggestions, textValue: value }));

                }


                then print out the suggestions list:



                   renderSuggestions () {
                const {suggestions} = this.state;
                if(suggestions.length !== 0) {

                return(
                <div className="auto-suggestions">
                <ul>
                {suggestions.map((item) =>
                <li key={item} className="suggestion-item" onClick={()=>
                this.suggestionSelected(item)}>
                {item.map(({ value, isMatched}) =>
                {isMatched ?
                <span>{value}</span> :
                <strong>{value}</strong>
                }
                )}
                </li>)}
                </ul>
                </div>
                );
                }
                }





                share|improve this answer













                You have 2 problems to solve: (1) extract the matching substring in suggestions and (2) highlight the matching substring in your UI.



                You can use String.prototype.split instead of RegExp.prototype.test to split the string with matching regex and prepare necessary data for rendering:



                onTextChange = (e) => {
                const value = e.target.value;
                let suggestions = ;
                if(value.length > 0) {
                const regex = new RegExp(`${value}`, 'i');
                suggestions = this.items.sort().map(v => {
                const arr = v.split(regex);
                return arr.map(substr => ({
                value: substr,
                isMatched: regex.test(substr)
                }))
                });
                suggestions = suggestions.filter(arr => arr.some(({ isMatched}) => isMatched))

                this.setState(() => ({ suggestions, textValue: value }));
                }
                this.setState(() => ({ suggestions, textValue: value }));

                }


                then print out the suggestions list:



                   renderSuggestions () {
                const {suggestions} = this.state;
                if(suggestions.length !== 0) {

                return(
                <div className="auto-suggestions">
                <ul>
                {suggestions.map((item) =>
                <li key={item} className="suggestion-item" onClick={()=>
                this.suggestionSelected(item)}>
                {item.map(({ value, isMatched}) =>
                {isMatched ?
                <span>{value}</span> :
                <strong>{value}</strong>
                }
                )}
                </li>)}
                </ul>
                </div>
                );
                }
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 2 at 4:36









                blazblaz

                1,692916




                1,692916






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000917%2fhow-to-apply-highlighting-match-characters-within-the-autosuggestion-list-in-rea%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Monofisismo

                    Angular Downloading a file using contenturl with Basic Authentication

                    Olmecas