2

I want to use google custom search engine in my React application. But I have a problem to apply it.

I checked in google website that the code is

<script>
  (function() {
    var cx = '008391824253360889328:j5posmpyok0';
    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>

But I have no idea how to change it into jsx that can use in React.

Can anyone help? Thanks.

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

You don't have to change anything. You can run it directly.

For Example:

conponentDidMount() {
  (function() {
    var cx = '008391824253360889328:j5posmpyok0';
    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);
  })();
}

But actually if you check the code that you got from google; its just adding a script tag. You can just add it manually too.

<script async="true" src="https://cse.google.com/cse.js?cx=008391824253360889328:j5posmpyok0" type="text/javascript"></script>

2 Comments

Thanks. Additionally, how to add such <gcse:searchbox></gcse:searchbox> into render() function in JSX. Because "<gcse:searchbox></gcse:searchbox>" are xml and cannot be used in jsx.
@VictorDiao You have 2 options I think. One is described here saying that you can use dangerouslySetInnerHTML but its dangerous. Second one is here you can use Html5 div tags for search.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.