How to include google custom search box in an React component

限于喜欢 提交于 2019-12-02 09:23:25

This perfectly works for me. Add a form element in your react and modify the snippet as shown below. react return. Add a form element tag try it. it works for me.

<form method = "get" title = "Search Form" action="https://cse.google.com/cse/publicurl">
 <div>
    <input type="text" id="q" name="q" title="Search this site" alt="Search Text" maxlength="256" />
    <input type="hidden" id="cx" name="cx" value="013626029654558379071:ze3tw4csia4" />
   <input type="image" id="searchSubmit" name="submit" src="https://www.flaticon.com/free-icon/active-search-symbol_34148" alt="Go" title="Submit Search Query" />
 </div>
</form>

I think I have a solution for you without using dangerouslySetInnerHTML. Put your code in the componentDidMount block and append to the element with jQuery like so:

componentDidMount(){
const embedcode = `<script>
      (function() {
        var cx = '013626029654558379071:ze3tw4csia4';
        var gcse = document.createElement('script');
        gcse.type = 'text/javascript';
        gcse.async = true;
        gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(gcse, s);
      })();
    </script>
    <gcse:search></gcse:search>`

  $('#gsearch').html(embedcode)
  }

And your DOM element:

<div id='gsearch'>
</div>

Still debugging some styling stuff, but this works!

Best, Patrick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!