Integrating on React

Hi team,

I’m working with a client who is trying to integrate the Answers Search Bar onto their site that is built on React.

To add the search bar to the page the integration guide instructs to add <div class="search_form"></div>. Because their site is on React and Nextjs this won’t work.

They’ve suggested using className or using dangerouslySetInnerHTML to put the html directly on the page but are still running into issues.

I wanted to check in with the community to see if anyone else has run into this issue before and how we should proceed?

Hey Henry,

Thanks for posting! React is so commonly used to build sites; it’s great that you asked.

The way we’ve seen this done in the past is using the componentDidMount method on a React component. The Answers script and ANSWERS.init can be added right there.

Here’s an example. (Replace the API key, experienceKey and redirect URL):

class SearchBarContainer extends React.Component {
  render() {
    return <div className="SearchBarContainer"></div>;
  }

  componentDidMount() {
    const answersScriptPromise = new Promise((resolve, reject) => {
      const answersScript = document.createElement('script');
      document.body.appendChild(answersScript);
      answersScript.onload = resolve;
      answersScript.onerror = reject;
      answersScript.async = true;
      answersScript.src = 'https://assets.sitescdn.net/answers/v1.6/answers.min.js';
    });

    answersScriptPromise.then(() => {
      ANSWERS.init({
        apiKey: 'REPLACE_ME_API_KEY',
        experienceKey: 'REPLACE_ME_EXPERIENCE_KEY',
        onReady: function() {
          ANSWERS.addComponent('SearchBar', {
            container: '.SearchBarContainer',
            redirectUrl: 'REPLACE_ME_REDIRECT_URL'
          });
        }
      });
    });
  }
}
1 Like

Thank you, Alexis! This did the trick and got my client up and running.

As a follow-up, my client is now trying to increase the width of their search bar and is struggling to target the correct object. I’m not sure if this issue is related to React but if it is do you have any guidance on how to target the search bar width? Screenshot of their unsuccessful attempt below.

Thank you again!

Oh that’s great to hear! I think if they target the element .yxt-SearchBar, that should do the trick. That would look like

.YextBar {
  .yxt-SearchBar {
    width: 500px; 
  }
}

Best of luck!
Alexis

1 Like

I am trying to do something similar but on the salesforce experience cloud site. Can you help in bringing up the Yext search bar on the Salesforce Experience builder site?

Hi Prasanna,

I saw you posted this same question as a new topic, which it seems like it is, and it got a response there!

Hi @Alexis_Grow , this is a great solution if you only need one Search Bar on a page. Is there a solution if you need multiple Search Bars on one page? I am running into issues with the Answers scripts running multiple times causing failures to add the components. Thanks!