Ad

Implementing Facebook Comments Plugin In ReactJS App

- 1 answer

I'm trying to load the facebook comments plugin in a ReactJS app that's currently using React Router.

If I put the facebook init code inside my page's componentDidMount() method, it loads the first time. But after going to another page and then going back to it again, it doesn't load the plugin at all.

Is there something that I need to do to make it appear all the time?

I'm thinking I need to remove the facebook init and reinitialize again. But that doesn't feel right.

Any suggestions? Below is my code of my component

```

import React, { Component } from 'react';
import SlidingPanels from '../components/SlidingPanels';

export class Feedback extends Component {
    constructor() {
        super();
    }

    componentDidMount() {
        $(window).scrollTo(0, '0.5s');

        window.fbAsyncInit = function() {
            FB.init({
                appId      : '115517331888071',
                cookie     : true,  // enable cookies to allow the server to access the session
                xfbml      : true,  // parse social plugins on this page
                version    : 'v2.5' // use version 2.1
            });
        }.bind(this);

        // Load the SDK asynchronously
        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));
    }

    render() {
        return (
            <div>
                <div className="fb-comments" data-target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="https://www.facebook.com/cna.net.au/" data-numposts="10"></div>
            </div>
        );
    }
}

``

Thanks, John.

Ad

Answer

You only need to initialize the JavaScript SDK once, and since componentDidMount only gets called once it´s fine where it is. Try putting FB.XFBML.parse() in componentDidUpdate:

componentDidUpdate() {
    FB.XFBML.parse();
}

I am not sure if this is the best solution, but it should work.

Ad
source: stackoverflow.com
Ad