I have been using the documentation from https://developers.facebook.com/docs/plugins/like-button/ to create a like button in my react web app. followed the documentation and generated the script and div.
Added the Script just below the body tag in the index.html as below.
<body>
<div id="fb-root"></div>
<script async defer crossOrigin="anonymous"
src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v11.0" nonce="pyP98Sf3"></script>
Then in the App.js, the below "fb-like" div placed in the default path as below works with no issues.
function App() {
return (
<Router>
<div>
<Route path='/' exact render={() => (
<Items items={items}/>
<div className="fb-like" data-href="http://localhost:3000/something"
data-width="" data-layout="standard" data-action="like" data-size="small" data-share="true"></div>
However, when my "fb-like" div is placed inside a another path as below, the like button doesn't shows up when I navigate to the page. It does show up if I navigate to the page and refresh it.
<Route path='/item-detail/:handle' render={()=>(
<>
<div className="fb-like" data-href="http://localhost:3000/item-detail/Chocolate%20Cake"
data-width="" data-layout="standard" data-action="like" data-size="small" data-share="true"></div>
<ItemDetail/>
</>
I really don't understand the reason behind this behavior. Appreciate if someone could help me out with a solution to this.
I was able to resolve this issue by having the DOM element inside the ItemDetails component and inserting the Script using the useEffect hook. Removed the Script in the HTML file body.
const ItemDetail = () => {
const {handle} = useParams()
const location = useLocation()
const loadScript = () => {
let script = document.createElement("script");
script.setAttribute("crossOrigin","anonymous");
script.src = "https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v11.0";
script.setAttribute("nonce","pyP98Sf3");
script.type = "text/javascript";
document.body.append(script);
}
useEffect(loadScript, [])
return(
<div className="fb-like" data-href="http://localhost:3000/item-detail/Chocolate%20Cake"
data-width="" data-layout="standard" data-action="like" data-size="small" data-share="true"></div>
)
}
A post "Loading Scripts on specific component (Route) in React" from Kaushal Madani helped me come up with the idea of inserting the script when the component mounts.
link - Loading Scripts on specific component (Route) in React