Add AddThis to React component

Replace addthis:url and addthis:title with data-addthis-url and data-addthis-title.


I put this div in to display the addthis buttons.

<div className="addthis_inline_share_toolbox" data-url={  `http://[Your URL]` } data-title={ `[Your Title]` }></div>

But I also needed to load the javascript after the component mounted or the buttons never display. I assume if you add the javascript to your template that it's loading before the share_toolbox is loaded.

componentDidMount() {
    setTimeout( () => {
      var addthisScript = document.createElement('script');
      addthisScript.setAttribute('src', 'http://s7.addthis.com/js/300/addthis_widget.js#pubid=[your id here]')
      if (document.body) document.body.appendChild(addthisScript)
    });

  },

In addition to the data attribute changes you should use the addthis.layers.refresh() method to dynamically refresh/load your AddThis components:

 render() {
    return (
        <div className="addthis_inline_share_toolbox" 
            data-url={this.props.myurl} 
            data-title="Check out this URL"
            >
        </div>
    );
 }

Then in componentDidMount():

 componentDidMount() {
     addthis.layers.refresh();
 }

EDIT: The above method is the initial approach i took and does initialise the add this widget however, the widget seems to not update the data-url when the prop is changed. even if i call addthis.layers.refresh(); again after a props update

Dynamic update solution:

In my render method:

// Don't use data attributes
<div className="addthis_inline_share_toolbox"></div>

Use the lifecycle methods:

componentDidMount() {
    addthis.layers.refresh(); // important! init the add this widget
    addthis.update('share', 'url', 'my-initial-url'); // update with initial prop value
}

componentDidUpdate() {
    addthis.update('share', 'url', this.props.myurl); // update with prop value
}

componentWillReceiveProps(nextProps) {
    addthis.update('share', 'url', nextProps.myurl); // update with prop value
}

Here is how I did it:

Please, note that I'm using the inline share toolbox.

Thanks @Mark for addthis.update and to @jvoros for react-load-script

import React, { useEffect } from 'react';
import Script from 'react-load-script';

const AddThis = (props) => {
    useEffect(() => {
        if (window.addthis) {
            window.addthis.update('share', 'url', props.url); 
        }
    }, [props.url]);

    const handleAddthisLoaded = () => {
        window.addthis.init();
        window.addthis.update('share', 'url', props.url);
    };

    return (
        <>
        <div className="addthis_inline_share_toolbox"></div>
        <Script
            url="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-xxxxxxxxxxxxxxxx"

            onLoad={handleAddthisLoaded} />
       </>                  
    );
}

export default AddThis;