Giter VIP home page Giter VIP logo

react-twitter-embed's Introduction

React Twitter Embed Component

NPM Storybook Build Status Known Vulnerabilities JavaScript Style Guide License

React Twitter Embed Component

Simplest way to add Twitter Widgets to your react project.

Demo and Examples

https://saurabhnemade.github.io/react-twitter-embed/

Install

npm install --save react-twitter-embed

Usage

import { TwitterTimelineEmbed, TwitterShareButton, TwitterFollowButton, TwitterHashtagButton, TwitterMentionButton, TwitterTweetEmbed, TwitterMomentShare, TwitterDMButton, TwitterVideoEmbed, TwitterOnAirButton } from 'react-twitter-embed';

Adding Timeline:

 <TwitterTimelineEmbed
  sourceType="profile"
  screenName="saurabhnemade"
  options={{height: 400}}
/>

Adding Tweet:

<TwitterTweetEmbed
  tweetId={'933354946111705097'}
/>

Adding Share Button:

  <TwitterShareButton
    url={'https://facebook.com/saurabhnemade'}
    options={{ text: '#reactjs is awesome', via: 'saurabhnemade' }}
  />

Adding Mention Button:

  <TwitterMentionButton
    screenName={'saurabhnemade'}
  />

Adding Hashtag button:

  <TwitterHashtagButton
    tag={'cybersecurity'}
  />

Adding follow button:

  <TwitterFollowButton
    screenName={'saurabhnemade'}
  />

Adding Moment:

  <TwitterMomentShare
    momentId={'650667182356082688'}
  />

Adding Direct Messaging Button:

  <TwitterDMButton
    id={1364031673}
  />

Adding Twitter Video:

  <TwitterVideoEmbed
    id={'560070183650213889'}
  />

Adding Twitter On Air Button:

  <TwitterOnAirButton
    id={'560070183650213889'}
  />

Explore All Options by Twitter Widgets API:

  https://developer.twitter.com/en/docs/twitter-for-websites/javascript-api/overview

License

MIT © saurabhnemade

Copyright (c) 2022

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

react-twitter-embed's People

Contributors

michelgotta avatar nickfoden avatar pcorpet avatar saurabhnemade avatar shawncholeva avatar teimurjan avatar

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

react-twitter-embed's Issues

ReactDOMServer not render to tweets

I'm trying to render embed tweets with ReactDOMServer.renderToString but it doesn't work.

  tweet = x =>
    ReactDOMServer.renderToString(
      <div>
        <TwitterTweetEmbed tweetId={x} />
      </div>
    );

How can I render tweets ?

Callback after tweet loading

Could you add a callback for TwitterTweetEmbed component firing after a tweet has been loaded?
I'd like to add a progress spinner to my app, and I need to hide it before a tweet will be shown.
Thanks.

autoHeight doesn't resize if window changes

using autoHeight for example in TwitterTimelineEmbed, properly fits height, until you resize window and it does not. if you reload the page and cause the components to rerender it will fit height again.

`script.js` dependency causes security check failure

Looks like the subject dependency (https://github.com/ded/script.js) hasn't been maintained anymore; last commit on on Oct 1, 2018.

Retire.js shows known vulnerabilities for 3rd-party libs:

> retire
retire.js v2.0.3
Downloading https://raw.githubusercontent.com/RetireJS/retire.js/master/repository/jsrepository.json ...
Downloading https://raw.githubusercontent.com/RetireJS/retire.js/master/repository/npmrepository.json ...
..../node_modules/scriptjs/vendor/jquery.js
 ↳ jquery 1.5.2
jquery 1.5.2 has known vulnerabilities: severity: medium; CVE: CVE-2011-4969, summary: XSS with location.hash; https://nvd.nist.gov/vuln/detail/CVE-2011-4969 http://research.insecurelabs.org/jquery/test/ https://bugs.jquery.com/ticket/9521 severity: medium; CVE: CVE-2012-6708, bug: 11290, summary: Selector interpreted as HTML; http://bugs.jquery.com/ticket/11290 https://nvd.nist.gov/vuln/detail/CVE-2012-6708 http://research.insecurelabs.org/jquery/test/ severity: medium; issue: 2432, summary: 3rd party CORS request may execute, CVE: CVE-2015-9251; https://github.com/jquery/jquery/issues/2432 http://blog.jquery.com/2016/01/08/jquery-2-2-and-1-12-released/ https://nvd.nist.gov/vuln/detail/CVE-2015-9251 http://research.insecurelabs.org/jquery/test/ severity: low; CVE: CVE-2019-11358, summary: jQuery before 3.4.0, as used in Drupal, Backdrop CMS, and other products, mishandles jQuery.extend(true, {}, ...) because of Object.prototype pollution; https://blog.jquery.com/2019/04/10/jquery-3-4-0-released/ https://nvd.nist.gov/vuln/detail/CVE-2019-11358 https://github.com/jquery/jquery/commit/753d591aea698e57d6db58c9f722cd0808619b1b

..../node_modules/scriptjs/vendor/yui-utilities.js
 ↳ YUI 2.8.2r1
YUI 2.8.2r1 has known vulnerabilities: severity: high; CVE: CVE-2012-5882; http://www.cvedetails.com/cve/CVE-2012-5882/ severity: high; CVE: CVE-2012-5881; http://www.cvedetails.com/cve/CVE-2012-5881/ severity: medium; CVE: CVE-2010-4710; http://www.cvedetails.com/cve/CVE-2010-4710/ severity: high; CVE: CVE-2010-4208; http://www.cvedetails.com/cve/CVE-2010-4208/ severity: high; CVE: CVE-2010-4207; http://www.cvedetails.com/cve/CVE-2010-4207/

react-twitter-embed dependency on script.js:

"scriptjs": "^2.5.9"

├┬ [email protected]
.....
│ └── [email protected]
...

Is it possible NOT to use script.js completely?

hat’s the best strategy for embedding multiple tweets (50-60) on a website?

I’m embedding around 50+ tweets via ‘react-twitter-widgets’. It takes 10+ seconds to load completely. The tweets are not rendered in sync manner, but rather rendered all at once, and this results in bad UX. What’s the best strategy do adopt here?

Also, while looking at the embedding, I stumbled upon https://cdn.syndication.twimg.com/tweet?id=TWEET_ID which returns data needed for rendering (media crop offsets, video thumbnails) which are not available in the actual api. Is it a good idea to use the https://cdn.syndication.twimg.com for getting renderable information and cache it in the server so embedding is faster?

Installation Error

code ETARGET
npm ERR! notarget No matching version found for [email protected]
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

node : 8.x.x
react : 15.x.x

Twitter No Longer Showing On Website

Upon opening the website today, I was confused as to why the twitter embeds were not working. I checked the code and it had NOT been changed in a long time. Suddenly, the twitter embeds are broken. Checking the javascript console reveals

Previously (working)

image

Current

image

Failed to load resource: net::ERR_BLOCKED_BY_CLIENT

image

ERESOLVE unable to resolve dependency tree

I tried to install this using npm i react-twitter-embed but got this error:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^17.0.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^15.0.0 || ^16.0.0" from [email protected]
npm ERR! node_modules/react-twitter-embed
npm ERR!   react-twitter-embed@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\{user}\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\{user}\AppData\Local\npm-cache\_logs\2021-02-21T14_45_35_858Z-debug.log

Anyone have any idea what to do now?

Making TwitterTweetEmbed draggable (in React)

This is quite an open question and I hope the title explains itself.
I am attempting to do this in quite a simple fashion with no success. Is there any way that this can be done?

{tweets.map(tweet => { return <TwitterTweetEmbed draggable onDrag={(e) => onDrag(e, tweet)} className="embeddedTweet" tweetId={tweet} onClick={console.log} /> })}

Twitter Timelines are down.

@saurabhnemade I use a fork of this library on my site. I am getting the same MIME type error though as you are on your storybook site.

Refused to execute script from 'https://cdn.syndication.twimg.com/timeline/profile?callback=__twttr.callbacks.tl_i0_profile_rahul581_old&dnt=false&domain=saurabhnemade.github.io&lang=en&screen_name=rahul581&suppress_response_codes=true&t=1780888&tz=GMT-0400&with_replies=false' because its MIME type ('') is not executable, and strict MIME type checking is enabled.

Please, if you know where this is coming from, or can shed any light on why this is happening, let us know thank you.

@michelgotta
@pcorpet
@NickFoden
@ShawnCholeva
@teimurjan

Detect clicks on follow buttons

Issue for PR #34

Expected behaviour

Being able to know when a TwitterFollowButton is pressed, by passing an onClick callback function as a prop.

Use case

Mostly tracking and user feedback.

Web pack is throwing an error when trying to build bundle js

Getting a few errors thrown by web pack which look like this

ERROR in ./node_modules/react-twitter-embed/dist/index.es.js
Module not found: Error: Can't resolve '@babel/runtime/helpers/esm/possibleConstructorReturn'

Not sure what the issue is

Error on rendering TwitterTimelineEmbed using React 16.1.1

I was having this error message for all the components:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `TwitterTimelineEmbed`.

image

Then I updated to react 16.2.0 and it worked. Maybe this a dependency, but I'm still in a learning phase for React so I can't tell that for sure.

I hope that helps! Thanks!

div inside p

Hi,

The TwitterTweetEmbed component is generally used inside blocks of text, that is, inside p elements. Therefore it would be best if it wouldn't rely on div elements internally or at least allow the consumer to pass a different element. Currently, react complains with:

Warning: validateDOMNesting(...): <div> cannot appear as a descendant of <p>.
    in div (created by TwitterTweetEmbed)
    ....

Anyways, thanks for the lib!

TwitterTimelineEmbed not rendering updated timeline when changing screenName prop

Changing screenName prop on TwitterTimelineEmbed does not change the displayed timeline. Looks like renderWidget is only called on mount, not on update.

I'm sure there are much cleaner ways to do this so I opted to not submit a pull request but here was my solution. I added the following to TwitterTimelineEmbed.js

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.screenName != prevProps.screenName) {
      /** reset embed Container */
      this.refs.embedContainer.innerHTML = ""

      let options = this.buildOptions()
      /** Append chrome options */
      options = this.buildChromeOptions(options)
      this.renderWidget(options)
    }
  }

How to center embedded tweet?

The embedded tweet sits on the left. I'm trying to center it by justify content, or wrap it inside a <div> tag and justify the <div> tag, neither works. I also tried display block, margin left auto, margin right auto, also doesn't work. How can I center it though?

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

String ref warning when using React in Strict Mode

When using TwitterTweetEmbed in React.StrictMode, I get this error in the console:

index.js:1 Warning: A string ref, "embedContainer", has been found within a strict mode tree. 
String refs are a source of potential bugs and should be avoided. 
We recommend using useRef() or createRef() instead. 
Learn more about using refs safely here: https://fb.me/react-strict-mode-string-ref
    in TwitterTweetEmbed

Passing handle as prop from parent state doesn't re-render

Hey there,

I'm passing the user name from the parent state, but updating that state doesn't trigger a re-render of the TimelineEmbed component:

<TwitterTimelineEmbed
sourceType="profile"
screenName={handle}
options={{height: 700}}
/>

Is there something I'm missing?

Thanks!

ReferenceError: document is not defined in scripts.js

I've pulled in the latest version of your library and am using webpack, nodemon and babel in my project. Nodemon and my build process crashes with the following message:

.../node_modules/react-twitter-embed/node_modules/scriptjs/dist/script.js:12
  var doc = document
            ^

ReferenceError: document is not defined
    at .../node_modules/react-twitter-embed/node_modules/scriptjs/dist/script.js:12:13
    at doc (.../node_modules/react-twitter-embed/node_modules/scriptjs/dist/script.js:8:72)
    at Object.<anonymous> (.../node_modules/react-twitter-embed/node_modules/scriptjs/dist/script.js:11:3)
    at Module._compile (module.js:643:30)
    at Module._extensions..js (module.js:654:10)
    at Object.require.extensions.(anonymous function) [as .js] (.../node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Module.require (module.js:587:17)
[nodemon] app crashed - waiting for file changes before starting...

State Update of parent component causes crash

Hi,

When updating the parent components state, we get:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it 
indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks
in the componentWillUnmount method.
    in TwitterMomentShare ...

Any advice?

Can this be done without placing the twitter script in the <head>?

It feels unnecessary to add a script to the head that then makes a bunch of calls on page load, even when the Twitter embed is not mounted. This utility, by simply including it in some conditionally-used component, adds at least 5 additional HTTP requests to the initial load of the page. This places third-party cookies.

Can this not be initialized on the fly, and then removed when unmounted?

[TwitterTweetEmbed] No target element specified.

I sometimes have an error No target element specified. Expected: ƒ(tweetId, target, [options]); in the console. I think this happens when:

  • I render a ReactTwitterEmbed component as part of my flow
  • The Twitter library gets downloaded/loaded slowly (for instance I'm on a slow network)
  • I remove the ReactTwitterEmbed from my DOM before the Twitter library gets loaded.

I'll send a PR to fix that.

Re-rendering component

I am using the TwitterTweetEmbed component with a variable for the tweetId, in this manner:

<TwitterTweetEmbed tweetId={item.postID} placeholder="Loading" />

I have a <p>{item.postID}</p> along with this.

On a state change, the item.postID changes, which is reflected in the <p> tag, but the <TwitterTweetEmbed> still shows the tweet related to the previous postID.
Anything needed to ensure that the component re-renders?

Cannot read property 'parentNode' of undefined

I'm getting an error when using react twitter embed

Cannot read property 'parentNode' of undefined

Code it fails on:
if (this.props.autoHeight) { options.height = this.refs.embedContainer.parentNode.offsetHeight }

I tried removing the auto height that we passed in but users are still seeing the bug. Any ideas?

Show Example for hide media on embed

Took me a minute to figure out how to hide media on embedded tweet.

Was not clear that you pass:

options={{ cards: "hidden" }}

I can submit PR if anyone else agrees. Be good to update storybook and the readme to show this use case as the link to twitter docs is not clear how to achieve hide media of embedded tweets:

Twitter docs
"Set an oEmbed query parameter of hide_media=true or add a data-cards="hidden" attribute to the resulting <blockquote> element to prevent expanded content display."

Express, and cross-site cookie SameSite attribute - Chrome warning

This is the one-liner that I use from your module:

<TweetEmbed id="1279402833310175232" />

, and this is the console output of Chrome Developer Tools:

A cookie associated with a cross-site resource at `http://twitter.com/` was set without the `SameSite` attribute. 
A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` 
and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at
https://www.chromestatus.com/feature/5088147346030592 and
https://www.chromestatus.com/feature/5633521622188032.

dependencies that I think might be relevant for you...
for front-end:

"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1",
"react-tweet-embed": "^1.2.2"

and for the server:

"cors": "^2.8.5",
"express": "^4.17.1",
node --version
v13.11.0
npm --version
6.14.5

Please tell me if it is something that I can fix, or if you need more of my development setup information.

onError or tweet not embedded

Hi,

When loading invalid tweet, for example it was deleted - the component is not showing anything.

is there a way to detect if there was an error loading it and if yes or call a function or set a placeholder component to display instead.

thanks.

TwitterTimelineEmbed does not display new or deleted tweets from a userID

TwitterTimelineEmbed works but it doesn't display new or deleted tweets from the userId. Is there a dynamic way to display users' timelines up to date so when the user tweets a new tweet or deletes it TwitterTimelineEmbed keeps track of the tweets and displays new or doesn't display deleted old tweets. Would I have to use the Twitter API to accomplish this?

Any advice or help will be appreciated :)

Timeline by hashtag?

Is there a way to get a timeline by hashtag? Instead of a user screen name or id, I would like to use a hashtag.
Is this possible?

link color not working

Is it just me/my local or is linkColor no longer working?
image

borderColor is working just fine as shown below (both the link and border should be a green color)
image

Thanks

Error when listing TwitterTweetEmbed

Hi !

I tried to list several tweets but when I updated the "IdList", the component did not update correctly and some previous tweets stayed with the new.

The code:

   this.getIdList().map((id, index) => (
                       <TwitterTweetEmbed
                           key={index}
                           tweetId={id}
                           options={{
                               cards: 'hidden',
                               conversation: 'none',
                               width: '100%',
                           }}  
                       />
                   ))

I tried with an outdated component named "react-twitter-widgets" and it works perfectly with the same logic:

this.getIdList().map((id, index) => (
                    <Tweet
                        key={index}
                        tweetId={id}
                        options={{
                            cards: 'hidden',
                            conversation: 'none',
                            width: '100%',
                        }}
                    />
                ))

MIME type mismatch for TwitterTweetEmbed

Getting the following error in the Chrome console when I attempt to render an embedded tweet:

Refused to execute script from 'https://cdn.syndication.twimg.com/tweets.json?callback=__twttr.callbacks.cb0&ids=zYthtQaw&lang=en&suppress_response_codes=true&theme=light&tz=GMT-0700' because its MIME type ('') is not executable, and strict MIME type checking is enabled.

Here is the code snippet:

<TwitterTweetEmbed tweetId="zYthtQaw"/>

Broken embeds containing js-openLink elements

Platform

Chrome Version 71.0.3578.98 (Official Build) (64-bit)
Was also able to reproduce on Android
Only occurs on mobile chrome views, not desktop
react-twitter-embed versions: 2.0.3 and 2.0.4

Problem Info

html gif:
ezgif-3-0b664dcce74b
Tweet ID: 842962082538704896
It seems to occur specifically with Javascript embedding of links within a tweet.
Example embedded a tag attributes:

js-openLink u-block TwitterCardsGrid-col--12 TwitterCard-container TwitterCard-container--clickable SummaryCard--small

js changing gif:
ezgif-3-5b442319ce51

Additional Info

It seems like this problem started out of nowhere, so it's most likely an issue with the most recent chrome update. The tweet embedding was working perfectly before and nothing has changed.

scroll bar always enabled

I am trying to disable scrollbar, tried with iframe attribute and setting pointer-events: none but it is not working

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.