Reputation: 161
I found one of amazing link Here that create widget for the Medium
posts.
Unfortunately I could not use the code in a react
website
example(A random medium author):
<div id="medium-widget"></div>
<script src="https://medium-widget.pixelpoint.io/widget.js"></script>
<script>MediumWidget.Init({renderTo: '#medium-widget', params: {"resource":"https://medium.com/@sunilsandhu","postsPerLine":2,"limit":4,"picture":"big","fields":["description","author","claps","publishAt"],"ratio":"landscape"}})</script>
Result is should be like this
How can I use the code in React website ?
Also I found a Angular version of this here but could not use in React app.
Thanks in advance
Upvotes: 3
Views: 1290
Reputation: 11
I dug into the code a little and found a method to use to unmount the widget. The result:
useEffect(() => {
window.MediumWidget.Init(widgetParams);
return () => {
window.MediumWidget.unmount();
};
}, []);
The unmount()
method can also be called in ComponentWillUnmount
if yer into that.
Upvotes: 1
Reputation: 702
Add the below code in your index.html
<script src="https://medium-widget.pixelpoint.io/widget.js"></script>
<script type="text/javascript">
function mediumWidget() {
MediumWidget.Init({
renderTo: "#medium-widget",
params: {
resource: "https://medium.com/@sunilsandhu",
postsPerLine: 2,
limit: 4,
picture: "big",
fields: ["description", "author", "claps", "publishAt"],
ratio: "landscape",
},
});
}
</script>
Add the following code in your component.
componentDidMount() {
try {
var widget = document.getElementById("medium-widget");
if (!!widget) {
window.mediumWidget();
}
}
catch(e){
window.location.reload();
}
}
return (<div id="medium-widget" ></div>)
If you have multiple pages in your react application and if you use history.push() for each page then when you come back the page which renders medium widget gives an error.
Therefore I add try-catch. we need to check whether the medium widget load or not. If the medium fails to load the page will reload again.
Upvotes: 1
Reputation: 415
In index.html
<script src="https://medium-widget.pixelpoint.io/widget.js"></script>
<script type="text/javascript">
function mediumWidget(){
MediumWidget.Init({renderTo: '#medium-widget', params: {"resource":"https://medium.com/@sunilsandhu","postsPerLine":2,"limit":4,"picture":"big","fields":["description","author","claps","publishAt"],"ratio":"landscape"}});
}
</script>
In your component
componentDidMount() {
window.mediumWidget();
}
render() {
return (<div id="medium-widget"></div>);
}
Upvotes: 7
Reputation: 628
just run the MediumWidget.Init
code at componentDidMount
life cycle or use the useEffect
hook to run it.
Upvotes: 1