Skip to content
Advertisement

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>

Advertisement

Answer

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

Advertisement