7

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>
squaleLis
  • 6,116
  • 2
  • 22
  • 30
markkazanski
  • 439
  • 7
  • 20

2 Answers2

10

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

MiguelSlv
  • 14,067
  • 15
  • 102
  • 169
evgeni fotia
  • 4,650
  • 3
  • 16
  • 34
  • What about cleaning up once the component unmouints? Will this work properly when mouning such a component again? –  Feb 08 '19 at 20:04
0

To expanciate on what @MiguelSlv wrote...

Place:

(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);
  })(),

In your App.js file. And place:

<script async src="https://cse.google.com/cse.js?cx=111:xxx">
in any your site's body section where you want the search box.