Code Monkey home page Code Monkey logo

react-twitter-widgets's Introduction

react-twitter-widgets

npm version npm downloads GitHub issues

Quick and easy Twitter widgets for React.

Available widgets: Timeline, Share, Follow, Hashtag, Mention, Tweet.

See below for usage.

Demo

Storybook / Live Demo

Installation

npm install --save react-twitter-widgets

Example

import { Timeline } from 'react-twitter-widgets'

// Tweet (without options)
<Tweet tweetId="841418541026877441" />

// Timeline (with options)
<Timeline
  dataSource={{
    sourceType: 'profile',
    screenName: 'TwitterDev'
  }}
  options={{
    height: '400'
  }}
/>

Usage

🔗 Official Twitter Documentation

Available widgets: Timeline, Share, Follow, Hashtag, Mention, Tweet

Timeline requires a dataSource object prop. The source type can be profile, list, or url. They each require their own co-fields; see Twitter documentation. NOTE that collection, likes, and moments will be deprecated on June 23, 2021.

Share requires a url prop.

Follow and Mention require a username prop. NOTE that the Twitter documentation now refers to this as screenName.

Hashtag requires a hashtag prop.

Tweet requires a tweetId prop. Ex. '511181794914627584'

Common Props

All widgets accept these props.

  • options (object)
    • To learn more about the available options, refer to the Twitter documentation. There are four options that are common to all widgets (lang, dnt, related, and via). There are further options for button widgets, tweet buttons, Timeline, and Tweet.
  • onLoad (function)
    • Called every time the widget is loaded. A widget will reload if its props change.
  • renderError (function)
    • Render prop. Rendered if widget cannot be loaded (no internet connection, screenName not found, bad props, etc).
    • Example: renderError={(_err) => <p>Could not load timeline</p>}

Lazy vs. Eager Loading

By default, the remote Twitter library will be lazy-loaded when the first widget renders. To instead load it eagerly, call eagerLoadTwitterLibrary.

import { eagerLoadTwitterLibrary } from "react-twitter-widgets";
eagerLoadTwitterLibrary();

Further Information

  • This library loads the remote Twitter for Websites library.
  • Twitter widgets are only loaded in the browser. A blank div will be rendered during SSR.

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request

Credits

License

MIT

react-twitter-widgets's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-twitter-widgets's Issues

When using react-router and navigating away from page where widgets are used, there is an uncaught null object error

Uncaught (in promise) TypeError: Cannot read property 'childNodes' of undefined(…)removeChildrenExceptLast @ AbstractWidget.js:75done @ AbstractWidget.js:63(anonymous function) @ Timeline.js:64

The code it's used in doesn't seem to break, but the console lights up with these (we use a lot of the widgets on a single page).

If it makes a difference, they are implemented in a bootstrap modal

how to hide timeline border and scroller

like this

<TwitterTimelineEmbed
sourceType="timeline"
id="539487832448843776"
theme="dark"
noHeader
noFooter
options={{height: 400}}
/>

noHeader bool - - Hide the header from timeline
noFooter bool - - Hide the footer from timeline
noBorders bool - - Hide the border from timeline
noScrollbar bool - - Hide the scrollbars

script fails to load in private mode

I noticed that in private mode on Firefox, the script doesn't load, which would then fail to render any of the tweets. Wondering if there's workaround.

Error for adblock user (syndication.twitter.com/settings blocked)

When adblock is activated users have this error :

Failed to load resource: net::ERR_BLOCKED_BY_CLIENT (syndication.twitter.com/settings)

Uncaught (in promise) Error: Network error.
at Object. (widgets.js:9)
at e (widgets.js:1)
at Object. (widgets.js:9)
at e (widgets.js:1)
at Object. (widgets.js:9)
at e (widgets.js:1)
at Object. (widgets.js:8)
at e (widgets.js:1)
at Object. (widgets.js:8)
at e (widgets.js:1)

tw.widgets is undefined on Firefox with tracking protection enabled

I am using this Gatsby starter which uses this library for the demo for one of the clickable links.

However, on Firefox (with tracking protection on), widgets.js is blocked which causes tw.widgets to be undefined but the larger problem is when Page 1 loads Page 2 (page with Twitter widgets) and the widget fails to load, the entire page fails to render and just leaves the page blank. Refreshing the page seems to make the page load but switching between page 1 and page 2 causes the page to be blank.

Stack trace:

The resource at “https://platform.twitter.com/widgets.js” was blocked because tracking protection is enabled.[Learn More]
the-butterfly-of-the-edge
Loading failed for the <script> with source “https://platform.twitter.com/widgets.js”.
the-butterfly-of-the-edge:1
[HMR] connected
client.js:87
The resource at “https://platform.twitter.com/widgets.js” was blocked because tracking protection is enabled.[Learn More]
the-butterfly-of-the-edge
Loading failed for the <script> with source “https://platform.twitter.com/widgets.js”.
the-butterfly-of-the-edge:1
TypeError: tw.widgets is undefined[Learn More]
Follow.js:59
The above error occurred in the <AbstractWidget> component:
    in AbstractWidget (created by Follow)
    in Follow (at UserInfo.jsx:9)
    in UserInfo (at post.jsx:36)
    in div (at post.jsx:29)
    in div (at post.jsx:24)
    in PostTemplate (created by ComponentRenderer)
    in ComponentRenderer (created by Route)
    in Route (created by MainLayout)
    in div (at index.jsx:44)
    in MainLayout (at index.js:6)
    in _default (created by ComponentRenderer)
    in ComponentRenderer (created by Route)
    in Route (created by withRouter(ComponentRenderer))
    in withRouter(ComponentRenderer) (created by Root)
    in ScrollContext (created by Route)
    in Route (created by withRouter(ScrollContext))
    in withRouter(ScrollContext) (created by Root)
    in Router (at root.js:143)
    in DefaultRouter (created by Root)
    in Root (at app.js:45)
    in AppContainer (at app.js:44)

React will try to recreate this component tree from scratch using the error boundary you provided, AppContainer.
index.js:2177
TypeError: tw.widgets is undefined
Stack trace:
Follow/_this.ready@http://localhost:8000/commons.js:50074:8
AbstractWidget/_this.loadWidget/<@http://localhost:8000/commons.js:49943:10
./node_modules/scriptjs/dist/script.js/</$script.ready@http://localhost:8000/commons.js:52299:8
AbstractWidget/_this.loadWidget@http://localhost:8000/commons.js:49931:8
componentDidMount@http://localhost:8000/commons.js:49960:8
commitLifeCycles@http://localhost:8000/commons.js:30634:16
commitAllLifeCycles@http://localhost:8000/commons.js:32305:10
callCallback@http://localhost:8000/commons.js:20970:10
invokeGuardedCallbackDev@http://localhost:8000/commons.js:21008:8
invokeGuardedCallback@http://localhost:8000/commons.js:21057:6
commitRoot@http://localhost:8000/commons.js:32444:10
completeRoot@http://localhost:8000/commons.js:33341:37
performWorkOnRoot@http://localhost:8000/commons.js:33291:12
performWork@http://localhost:8000/commons.js:33209:10
performSyncWork@http://localhost:8000/commons.js:33186:6
interactiveUpdates@http://localhost:8000/commons.js:33436:10
interactiveUpdates@http://localhost:8000/commons.js:22828:11
dispatchInteractiveEvent@http://localhost:8000/commons.js:25122:4
index.js:2177
The above error occurred in the <AbstractWidget> component:
    in AbstractWidget (created by Follow)
    in Follow (at UserInfo.jsx:9)
    in UserInfo (at post.jsx:36)
    in div (at post.jsx:29)
    in div (at post.jsx:24)
    in PostTemplate (created by ComponentRenderer)
    in ComponentRenderer (created by Route)
    in Route (created by MainLayout)
    in div (at index.jsx:44)
    in MainLayout (at index.js:6)
    in _default (created by ComponentRenderer)
    in ComponentRenderer (created by Route)
    in Route (created by withRouter(ComponentRenderer))
    in withRouter(ComponentRenderer) (created by Root)
    in ScrollContext (created by Route)
    in Route (created by withRouter(ScrollContext))
    in withRouter(ScrollContext) (created by Root)
    in Router (at root.js:143)
    in DefaultRouter (created by Root)
    in Root (at app.js:45)
    in AppContainer (at app.js:44)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://fb.me/react-error-boundaries to learn more about error boundaries.
index.js:2177
TypeError: tw.widgets is undefined[Learn More]
Follow.js:59
TypeError: tw.widgets is undefined[Learn More]
Follow.js:59

Rendering async

Sorry, this is kind of a basic support question rather than an actual issue.

After adding the Timeline component, I noticed my site seems to delay loading other things until the Timeline is finished loading. Is there any way to move that to not stop the main thread?

Does not work with react 18

Had to --force npm install & get babel errors

    node_modules/react-twitter-widgets/es/index.js:1:32:
      1 │ import _regeneratorRuntime from "@babel/runtime/regenerator";
        ╵                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  You can mark the path "@babel/runtime/regenerator" as external to exclude it from the bundle,
  which will remove this error.

1 error

Uncaught (in promise) Error: No target element specified. Expected: ƒ(tweetId, target, [options]);

Hello :)

i'm trying to implements a simple tweet element like this in my react app:

              <Tweet
                tweetId='1022854752315559937'
                options={{ cards:'hidden', align:'center'  }}
              />

It actually shows up correctly on the screen, but in the console i get the error:
Uncaught (in promise) Error: No target element specified. Expected: ƒ(tweetId, target, [options]);

I tried adding the parameter on the Tweet element but i still get the same error in the console.

Am i implementing something wrong?

Thanks!

It's a matter of using it in a Google Extension

In the development of Google Extension, prompted "Could not load remote twitter widgets js", I think it should need to be in the manifest file in the content_security_policy add some code, but I tried a few ways not solved!

Thank you.

Widget suddenly way taller than before?

Hi all,

I've just come back to a repo that uses this package and noticed that the twitter widget is way taller than before (9000 pixels high?!), when previously I was able to contain it to be about 500 pixels high.

My code is as follows:

        <Placeholder>
          {sectionInView && (
            <Timeline
              dataSource={{
                sourceType: "profile",
                screenName: "WonderWorksRB",
              }}
              options={{
                height: "530",
                width: "500",
              }}
            />
          )}
        </Placeholder>

And my CSS:

const Placeholder = styled.div`
  min-height: 530px;
`

Adding a max-height to Placeholder has no effect - in fact when I add a max-height property, the timeline protrudes beyond the wrapper div that contains this widget. I'm having similar issues with the width (it's no longer as responsive as it was) but at least adding a max-width property to the container seems to address the issue somewhat.

There is the tweetLimit value which I suppose could override the height of the widget but previously there was a Y-axis overflow scroll which was a much better solution from a UX perspective.

What has changed in the past month or two?

renderError not rendering for successive error tweets

So I am displaying tweets via next-previous navigation, and I noticed that when we have two successive tweets failing to fetch, the render error is invoked for the first one but there is no error rendered for the second one.

Demo

import React, { useState } from "react";
import "./styles.css";
import { Tweet } from "react-twitter-widgets";

export default function App() {
  const tweets = ["1338166052975497218", "000", "0010", "1337051123799232514"];
  const [index, setIndex] = useState(0);

  return (
    <div className="App">
      <button onClick={() => setIndex((index + 3) % 4)}>previous</button>
      <button onClick={() => setIndex((index + 5) % 4)}>next</button>
      <Tweet
        options={{ width: "120px%", theme: "dark" }}
        renderError={() => "Unable to fetch tweet"}
        tweetId={tweets[index]}
      />
    </div>
  );
}

how to hide cards in tweets and timeline ??

<Tweet tweetId={elementDetails.tweetId} options={{ theme: elementDetails.isDark ? 'dark' : 'light', width: elementDetails.styling.width - 20, height: elementDetails.styling.height - 30, }} renderError={() => ( <p> Could not load Tweet Please Check the Tweet URL or Tweet ID </p> )} />

I can't use onLoad function

Hi! I'm using this package for my current project, and somehow I want to add a loading state when rendering/fetching the timeline. I already read about the onLoad function but I do not know how to implement it. Please care to teach me how to use it? I'm just a junior dev. Thank you so much for the response!

Error handling?

I have a use case where I stream tweet IDs into an ElasticSearch database, then use your widgets to render tweets using these IDs. Alas, some of the IDs are from deleted tweets, which silently fail because you call .then() and not .catch() here.

I'm admittedly not super familiar with React and am not sure the best way of handling such errors; otherwise I'd submit a PR. 👍

Adding option for not showing follow count on follow button

Hi,

Thanks for a great tool. I wonder if it would be possible to add a prop to the Follow button to set whether the data-show-count option is set or not. That way you could set it to false if you didn't want the follow button to show the number of followers?

Thank you.

support grid template

The Twitter for Websites JavaScript library supports dynamic insertion of a collection displayed in a grid template using the twttr.widgets.createGridFromCollection function. Pass a collection ID, target container element, and optional options object to insert an embedded collection displayed in a grid template into your page.

Can I custom share button text?

Follow from this title. I'm not found parameter to solve this solution. Please suggest me.

In official documentation from twitter I can insert in a tag directly like this.

<a class="twitter-share-button"
  href="https://twitter.com/intent/tweet"
  data-size="large"
  data-text="custom share text"
  data-url="https://dev.twitter.com/web/tweet-button"
  data-hashtags="example,demo"
  data-via="twitterdev"
  data-related="twitterapi,twitter">
Tweet <-- I can exist my own button text here but this library can't
</a>

React.PropTypes and React.createClass decprecated

These will soon be deprecated for the latest version of React. This is a great package and has been really usually for our team. Do you have any intention of updating these? It would be really appreciated.

Updating Timelines for optional WidgetId, various sourceType

Thanks for your work on this module, @andrewsuzuki! I was trying to use it to create a timeline but as of June 2016 you can no longer create new timeline widgets -- and thus there's no widgetId available although it is required -- but widgets only need a screenName now. There are also several types of timelines and some have different syntax for specifying users.

I was going to make a PR to make widgetId optional but this seems like a broad enough change that some prior strategizing might be helpful. What do you think?

Dark theme option is not working on <Tweet/> component

Hey Andrew, thanks for this helpful library.

Adding options to the Tweet component (especially data-theme) is not working.

<Tweet tweetId={tweetId} options={{ dataTheme: "dark" }} />

Am I doing something wrong? it still renders in light mode.

o.hasIntersectionObserverSupport.s.IntersectionObserver.threshold Error

If anyone can point me in the right direction please - Here's the error log:

widgets.js:formatted:2291 Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
    at o (widgets.js:formatted:2291)
    at r._flush (widgets.js:formatted:3240)
    at widgets.js:formatted:687

super basic "react": "^15.6.1" list:

import { Tweet } from 'react-twitter-widgets';


let RenderRetweetedTweets = ({tweets}) => {
  let l = tweets.map(
    (retweeted_tweet_id) =>

      <div id="rrl-d1a"
           key={String(retweeted_tweet_id)}
      >
        <Tweet tweetId={retweeted_tweet_id}
               options={{
                 conversation: 'all',
                 cards: 'visible',
                 theme: 'light',
                 align: 'center'
               }}
        />
      </div>
  );
  return (
    <div id="rrl-d0a">
      {l}
    </div>
  );
};

Edit CSS styles of Timeline

How do we edit the CSS style of the Twitter widget?
Let's say we want to change the background colour of the Timeline...?

Twitter update breaking the options?

It looks like some update must have been done on Twitter's end because none of the options are working (e.g. noborder, noheader, etc). Is there an update you'll need to do to the Twitter lib?

Error: FeatureSwitchContext was not correctly initialized

Hello, so I am using the Twitter API where I retrieve the users profile info and display it alongside their tweets. And I am using the Tweet component where I pass in all the tweet ids to display each Tweet. And it is able to display the tweets properly. And I am using the renderError prop just in case their is an error and I am also using the onLoad prop. The way I am using the onLoad prop is that while its loading it shows an h1 element saying the tweet is loading, but as soon as the actual tweet loads in, it sets this state I set up to true which replaces the h1 element with the Tweet. And it is able to do so successfully, but for some reason I am getting this weird error, and it is coming from the react-twitter-widgets source code. Here is an image of what I am talking about:
Screenshot 2020-11-19 111637

Would you know what could be causing this issue and how it would be able to be fixed?

Widget configuration is not found

Im getting.

Widget configuration is not found. every time i try to use a widgetId different to 600720083413962752, is there a way to catch errors on the onLoad function?

Looking into the API reference it seems like a property element exists, maybe we can use it to check if the timeline is loaded itself.

eagerLoadTwitterLibrary import error

Module '"react-twitter-widgets"' has no exported member 'eagerLoadTwitterLibrary'.ts(2305)

Is there a solution to this for react with typescript?

Cannot read property 'widgets' of undefined

I am using your library in my webpack build package. Unfortunately I get a

Follow.js:62 Uncaught TypeError: Cannot read property 'widgets' of undefined
    at Follow.ready (http://localhost:8080/bundle.js:698:10)

My JavaScript code looks like:

import { Follow } from 'react-twitter-widgets';

export default function() {
  return <Follow username='TwitterDev' />;
}

I looked at my Chrome debug tools and saw that tw in tw.widgets.createFollowButton is undefined.

no support for grid type in collections

Per https://dev.twitter.com/web/embedded-timelines/oembed there are 2 ways collections can be displayed: list and grid

Collection timelines only. Set to grid to display Tweets in a grid layout

By default it's assumed they're list, but you can pass widget_type as grid to get a tile-based grid layout

But this code still produces a list not a grid:

<Timeline
  dataSource={{
    sourceType: 'collection',
    id: 'some_list_id'
  }}
  options={{
    chrome: 'noheader, nofooter, noborders',
    theme: 'dark',
    widget_type: 'grid',
    height: '400'
  }}
  onLoad={() => console.log('Timeline is loaded!')}
/>

Twitter Lists do not update with new tweets.

Hello,

I am having an issue where the twitter list will not append any new tweets unless i refresh the component completely.

Is this a limitation of the twitter widget or can i add something to make it update when a new item is in that list?

Thanks

Multiple timelines rendered if prop values change quickly

I'm using react-twitter-widgets inside Storybook with knobs, to change the account shown in a timeline.

With knobs, the props that get passed to Timeline can change very quickly - ie. simon360 will get passed very shortly after simon36. This creates a race condition: it seems like removeChildren gets called from AbstractWidget while rendering the simon360 timeline, before the timeline from simon36 gets rendered.

As a result, you can end up with more than one timeline in the DOM.

The ideal solution would be to somehow cancel any in-progress timeline loads when removeChildren runs, or less ideally, throttle the rendering call.

Able to reproduce in both Firefox and Chrome. If this issue isn't totally clear, I'll set up a proper demonstration of the issue with code examples.

Check stale time before Twitter request

Hi there!
Before anything, thank you for this contribution, makes everything easy and work perfectly fine.

However, I want to comment that there's no way to setup a stale time, a period to show just some cached data... I think it can be helpful, as the accounts usually do not update that frequently, for example an user that:

  • Navigates to the homepage and the feed is rendered
  • the user navigates to a detail page
  • the user comes back to the homepage: in this case I think we can spare the new request.

I wonder: is this a topic already discussed here? I did not found it in the issues list.
Do you think it worth the time to give it a try? I can take a look...

And again, thank you!

webp support

Is it possible to support usage of webp images?

update peer dependency to support React 17

Currently there is supported only React version 16 within peerDependencies.

It would be good to extend the support for v17 as there should not be expected any complications by doing so.

How to style inner elements?

This plugin works perfect, but I cannot figure out ho can I, e.g. remove background-color on hover for tweets? Is there a way to add a prop for <Timeline /> component to be able to style elements inside iframe?

errors in widgets.js with react 15.4

The timeline renders but I'm getting Uncaught errors in the console

Uncaught (in promise) TypeError: Cannot read property 'classList' of null
at Object.u [as present] (widgets.js:8)
at t.hasRootClass (widgets.js:9)
at t.recalculateBreakpoints (widgets.js:10)
at t. (widgets.js:10)
at widgets.js:9

Uncaught (in promise) Error: sandbox not initialized
at t.removeRootClass (widgets.js:9)
at t.recalculateBreakpoints (widgets.js:10)
at t. (widgets.js:10)
at widgets.js:9

onLoad not showing anything

onLoad={() => { return ( <NoShow> Could not load Tweet Please Check the Tweet URL or Tweet ID </NoShow> ); }}

renderError={() => ( <NoShow> Could not load Tweet Please Check the Tweet URL or Tweet ID </NoShow> )}

renderError works perfectly

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.