Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Facebook comments plugin in ReactJS app

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-href="https://www.facebook.com/cna.net.au/" data-numposts="10"></div>
            </div>
        );
    }
}

``

Thanks, John.

like image 765
John Fu Avatar asked Jan 07 '16 11:01

John Fu


People also ask

Will Facebook stop supporting React?

As of January 19, 2021, Facebook React Native SDK will no longer be officially supported by Facebook.


1 Answers

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.

like image 196
andyrandy Avatar answered Sep 21 '22 01:09

andyrandy