Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed Google Custom Search in React App?

I need to embed a JS widget in a React app. Is there a way to do it?

The JS widget is Google Custom Search:

  (function() {
    var cx = '111:xxx';
    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);
  })();
<gcse:search></gcse:search>
like image 310
markkazanski Avatar asked Dec 10 '18 17:12

markkazanski


1 Answers

use componentDidMount

componentDidMount() {
  (function() {
    var cx = '111:xxx';
    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);
  })();
}

and use

<div class="gcse-searchbox" data-resultsUrl="http://www.example.com"
data-newWindow="true" data-queryParameterName="search" />`

instead of <gcse:search></gcse:search> according to the documentation

like image 69
evgeni fotia Avatar answered Sep 30 '22 04:09

evgeni fotia