Facebook event plugin in react.js disappears after click to another page link

892 views Asked by At

I've been trying to get the Facebook event plugin to work in my create-react-app and can't figure it out.

In my Events.js file I added this:

<div id="fb-root"></div>
<div className="fb-page" data-href="https://www.facebook.com/[artistname]" data-tabs="events"
data-width="" data-height="" data-small-header="true" data-adapt-container-width="true"
data-hide-cover="false" data-show-facepile="true">
  <div className="fb-xfbml-parse-ignore">
    <blockquote cite="https://www.facebook.com/[artistname]/events">
      <a href="https://www.facebook.com/[artistname]/events" target="_blank">[artistname] - coming events</a>
    </blockquote>
  </div>
</div>

The SDK is imported in index.html

Everything works fine when I load the actual events page, but after clicking on "Start" and going back to "Events" the plugin disappears. Some say to put

componentDidMount(){
  window.FB.XFBML.parse()};
}

in the component, but my Event.js is a function.

I'm running out of google links now, any help is appreciated.

1

There are 1 answers

1
xyhhx On

Easiest solution is to use the iframe option, but that doesn't directly answer your question.

Answer 1: use the useEffect hook

Example CodeSandbox here

Instead of using the componentDidMount lifecycle method from class components, you can use the useEffect hook:

  useEffect(() => {
    window.FB.XFBML.parse();
  }, []);

This will call window.FB.XFBML.parse once per render.

Note: You may want to wrap that with an if (window.FB) to catch instances where window.FB didn't load

Answer 2: Convert to class component

You can of course convert your component to the old class based style:

export default class Events {
  componentDidMount() {
    window.FB.XFBML.parse();
  }

  render() {
    return (
      <>
        {/* ... */}

        <div
          className="fb-page"
          data-href={`https://www.facebook.com/${artistName}`}
          data-tabs="events"
          data-width=""
          data-height=""
          data-small-header="true"
          data-adapt-container-width="true"
          data-hide-cover="false"
          data-show-facepile="true"
        >
          <div className="fb-xfbml-parse-ignore">
            <blockquote cite={`https://www.facebook.com/${artistName}/events`}>
              <a
                href={`https://www.facebook.com/${artistName}/events`}
                target="_blank"
              >
                {artistName} - coming events
              </a>
            </blockquote>
          </div>
        </div>
      </>
    );
  }
}