unable to load velocity with scrollmagic and react - reactjs

I have a react project and I'd like to use scrollmagic with the velocity plugin. Here's what I did from terminal once I already have a react project set up
npm install scrollmagic
npm install velocity-react
This is what my src/App.js looks like
import React, { Component } from 'react';
import ScrollMagic from 'scrollmagic';
import Velocity from 'velocity-react';
class App extends Component {
componentDidMount() {
// init controller
var controller = new ScrollMagic.Controller();
// build scene
var scene = new ScrollMagic.Scene({triggerElement: "#trigger"})
// trigger a velocity opaticy animation
.setVelocity("#animate", {opacity: 0}, {duration: 400})
.addIndicators() // add indicators (requires plugin)
.addTo(controller);
}
render() {
return (
<div>
<div className="spacer s2"></div>
<div className="spacer s2"></div>
<div id="trigger" className="spacer s0"></div>
<div id="animate" className="box1 blue">
<p>Now you see me...</p>
view source
</div>
<div className="spacer s2"></div>
</div>
);
}
}
export default App;
Then I ran my webpack command without error. Now when I look in my Chrome browser, I see a blank page. And the debug console gives me these errors:
15:56:08:694 (ScrollMagic.Scene) -> ERROR calling setVelocity() due to
missing Plugin 'animation.velocity'. Please make sure to include
plugins/animation.velocity.js
15:56:08:694 (ScrollMagic.Scene) -> ERROR calling addIndicators() due
to missing Plugin 'debug.addIndicators'. Please make sure to include
plugins/debug.addIndicators.js
How do you get these Velocity and Indicator functiosn to work with scrollmagic in a reactjs environment?

I came across this issue in a recent project. There are a couple of hoops you need to jump through to get it up and running.
1) I had to add aliases for all the imports I wished to make. This was done via the webpack.app.config.js file.
module.exports = options => ({
resolve: {
alias: {
"TweenMax": "gsap/src/uncompressed/TweenMax.js",
"TimelineMax": "gsap/src/uncompressed/TimelineMax.js",
"ScrollToPlugin": "gsap/src/uncompressed/plugins/ScrollToPlugin.js",
"ScrollMagic": "scrollmagic/scrollmagic/uncompressed/ScrollMagic.js",
"ScrollMagicAddIndicators": "scrollmagic/scrollmagic/uncompressed/plugins/debug.addIndicators.js",
"ScrollMagicGSAP": "scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap.js"
}
}
});
2) Once I had added this. I had to have the correct order of imports inside my runtime script.
import * as ScrollMagic from 'scrollmagic';
import 'TimelineMax';
import 'ScrollMagicGSAP';
import 'ScrollMagicAddIndicators';
This all worked with the following dependencies.
"gsap": "^1.20.3",
"scrollmagic": "^2.0.5",
Hope this helps.

Related

Not able to import marked js from #types.marked in react app

I have installed marked js in react app using npm install --save #types/marked.
Below is the react component:
import { marked } from "marked";
// import { marked } from "../../node_modules/#types/marked/index";
// import { marked } from "../../node_modules/#types/marked/index.mjs";
// import * as marked from "marked";
const MyPage : React.FC = () => {
return (
<div>
{ marked("Hello world from MyPage.") }
</div>
)
}
export default MyPage;
As you can see in below screenshot of tooltip in VS code, the intellisence knows where the actual function is.
But the app does not compile, I get the following errors (corresponding to different styles of imports for marked in comments):
Module not found: Can't resolve 'marked' in 'D:\coding\myblog\blog-frontend\src\app-components'
Module not found: Can't resolve '../../node_modules/#types/marked/index.mjs' in 'D:\coding\myblog\blog-frontend\src\app-components'
Basically, what ever string that I am providing after from in import statement, react tries to find it in ~/src/app-components. But all other imports are working fine (like my servies, models etc).
I know it's a bit late, but I had the same issue and could resolve it with:
npm install --save marked
In your package.json file you can look up dependencies if it's correct installed.
I used npm install -g marked at first and that wasn't really working despite getting the feedback that it was installed.

Full-fledged PDF.js viewer in React

I'm looking to use the full-featured PDF.js in a React component in a Next.js project, as seen in Firefox and as on this online demo. Some important features here are being able to navigate to a certain page number by typing it in, and searching for text in the PDF. Is there a React component available for that?
The library react-pdf is nice for rendering a single page, but doesn't provide a toolbar or a convenient way of lazily loading pages in a scrollable view.
Similar to the questions How to use full PDF.js viewer with toolbar in webpack and Vuejs? (where the accepted answer provides a Vue component) and Embed Full Mozilla pdf.js viewer in vue.js ( using webpack via vue-cli ), but for React.js.
I tried including including /web/viewer.html as part of the inner HTML of a React component by doing the following, but it didn't work out.
Download the latest release and extract it to a folder part of my Next.js project (which I called pdfjs). I tried several folders, such as /client, /client/components, /pages, /node_modules, and /.
Run npm install --save-dev html-loader
Use this Webpack loader that parses HTML files, by changing next.config.js to the following:
module.exports = {
// …
webpack: (config, options) => {
config.module.rules.push({
test: /\.html$/,
exclude: /node_modules/,
use: { loader: 'html-loader' }
});
return config;
},
}
Create a simple page under /pages as follows:
import React from 'react';
import PdfViewer from '../pdfjs/web/viewer.html'
export default function () {
return (
<div className="content" dangerouslySetInnerHTML={{ __html: PdfViewer }} />
);
};
After running next in terminal to start a dev server and navigating to that page in the browser, I get an error about the JavaScript heap running out of memory.
Even if my computer had enough memory, I'm not sure that this would actually result in the PDF rendering – not to mention the danger of using dangerouslySetInnerHTML. It looks like a better solution would probably be to have an actual React component rather than trying to embed an HTML file.
I think this might be more of what your after. I wrapped it in a component for you already but this is a document viewer which can view PDF documents with out much work.
import React,{ Component } from 'react';
import ReactDOM from 'react-dom';
class DocView extends React.Component{
constructor(props){
super(props);
}
render(){
var url = "https://docs.google.com/viewerng/viewer?url="+this.props.src+"&embedded=true";
return(
<iframe style={this.props.style} src={url}></iframe>
);
}
}
export default DocView;
CloudPDF offers a React PDF viewer. It is basically pdf.js but then pre-rendered on the server. This gives the possibility for lazy loading of large pdf files and still keeping performance. And by default has a nice layout for the viewer.
import CloudPdfViewer from '#openbook/cloudpdf-viewer';
export default function () {
return (
<CloudPdfViewer documentId="346467a6-fa61-43ad-b45a-d1fdc3da0007" width="100%" height="500px" />
);
};
Disclamer: I am working for CloudPDF and it is still a beta version.

How to show build datetime on my react web app using create-react-app?

tl;dr version - I want to show the date of deployment of the production application on the footer of my application so that the users know exactly when the application was last updated.
I want it to be automatic, but I can't think of a way to capture the current date time during build and then parse it into html (jsx) to show them.
Update - Btw, I use CRA and have no plans of ejecting from it! At least not for this.
Context - Why do I want this?
I have a production application in React that I don't have unrestricted access to. There were some issues raised on there and I was able to replicate it on my dev and I fixed the issues and deployed it (or I thought I did). But the issue remained on production and after more time debugging, I just asked for a lot of diagnostic information from them to check if there was something wrong with the production API or database etc. But it finally turned out that my deployment to production wasn't successful. I think that if I showed the last deployement date-time somewhere on the app, I could just ask that from the users rather than get into elaborate diagnostic information.
I'm a Create React App maintainer!
Starting in Create React App 2 (react-scripts#^2.0) you can accomplish this via macros.
First, install preval.macro:
$ npm install --save preval.macro # if using npm
$ yarn add preval.macro # if using yarn
Next, in the file you want to render a build timestamp in, include preval.macro:
import preval from 'preval.macro'
Finally, you can create a constant and use it in your app like so:
const dateTimeStamp = preval`module.exports = new Date().toLocaleString();`
Here's a full example:
import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
import preval from 'preval.macro'
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Build Date: {preval`module.exports = new Date().toLocaleString();`}.
</p>
</header>
</div>
)
}
}
export default App
The solution from joe-haddad is working well. Here is a drop-in component you can use like <VersionNumber />. This will display something like:
import React from 'react';
import moment from 'moment';
import packageJson from '../../../package.json';
import preval from 'preval.macro';
const buildTimestamp = preval`module.exports = new Date().getTime();`;
class Component extends React.Component {
getDateString = () => {
const lastUpdateMoment = moment.unix(buildTimestamp / 1000);
const formattedDate = lastUpdateMoment.format('DD.MM.YYYY HH:mm:ss');
return formattedDate;
};
render () {
return (
<div>
{packageJson.version}
{'.'}
{buildTimestamp}
{' '}
{'('}
{this.getDateString()}
{')'}
</div>
);
}
}
Component.propTypes = {};
Component.defaultProps = {};
export default Component;
Set a process environment using webpack. You can save the value to a local json file and read from it with an increment during the compilation.
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether we’re running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
REACT_APP_DATE_TIME: new Date().toDateString(),
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl,
}
);
// Stringify all values so we can feed into Webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;
The old solution will also work. Please check the code again. As i can see the proper value in my app.
A contribution to Joe Haddat's answer; if you want to illustrate the build date by using preval.macro in the viewer timezone instead of the environment timezone which builds the app, here is how to do it;
render() {
const buildDate = preval`module.exports = new Date();`
return (
<div>Build Date: {new Date(buildDate).toLocaleString()}</div>
)
}
This will save the build date, but turning it into a locale string will still happen on runtime, on the browser where the viewer timezone is used.

Webpack/react hot reload reloading whole page?

This is probably asked all the time, but I've tried every approach under the sun and can't find a solution.
I've created a repo to make it easier to get help. You can clone it, run npm install and then npm start:dev to see a quick local server on http://localhost:8080.
It works, and when I change a file (say, src/components/Note/Note.css) the app does reload. However, I want to only reload the component, not the whole page. I'm not sure what I'm doing wrong. Any help will be appreciated!
To debug issues like this, enable "Preserve log" in Chrome DevTools console settings to preserve console log across page refresh.
The error was:
Uncaught RangeError: Maximum call stack size exceeded
This was fixed once the following changes were made:
Remove new webpack.HotModuleReplacementPlugin() from plugins (as webpack-dev-server is started with --hot)
Also opt-out of babel transpiling ES6 modules by updating presets in .babelrc to ["react", ["env", { "modules": false }]].
"modules": false is to tell babel to not compile import/exports and let webpack handle it as described here and here (Check step 3.3.c).
For anyone using Next.js:
If you edit a file in pages/, the whole page will reload. Bummer, state is lost.
If you edit a file in components/, only the relevant module will re-load (i.e., hot reload as you expect).
My recommendation: keep the files in your pages/ folder simple.
Iterate your design/details in a component file in the components/ folder.
For example:
// pages/welcome.jsx
import WelcomePage from "../components/welcomePage";
export default function Welcome() {
return <WelcomePage />;
}
// components/welcomePage.jsx
import React from "react";
import Layout from "./layout";
import { useContext, useEffect, useState } from "react";
import PlayerContext from "../../context/playerContext";
export default function WelcomePage() {
const { songTitle } = useContext(PlayerContext);
return (
<Layout>
<div className="...">
<div className="...">
Welcome! Let's play {songTitle}.
</div>
</div>
</Layout>
);
}
Then you can go ahead and make small edits to components/welcomePage.jsx without losing state in your browser.

Sharepoint Framework cant find module

I had a project which used youtube-api-search in it. it works there fine.
I have created a sharepoint framework template with yeoman "yo #microsoft/sharepoint" and installed youtube api package as I did in previous project. but when I run this project I encounter an error like below;
Cannot find module 'youtube-api-search'
as I said its working in other react project do i need something specially to make it work here ?
I installed api via "npm i youtube-api-search --save-dev" command
here main component content;
import * as React from 'react';
import { css } from 'office-ui-fabric-react';
import styles from './Announcements.module.scss';
import { IAnnouncementsProps } from './IAnnouncementsProps';
//I have added only these 2 lines to default code
import YTSearch from 'youtube-api-search';
const YOUTUBE_API_KEY = "AIzaSyCI9gcceui5zcQDAEwbyv...";
export default class Announcements extends React.Component<IAnnouncementsProps, void> {
public render(): React.ReactElement<IAnnouncementsProps> {
return (
...
);
}
}
we can import modules in three methods
FIRST::Using Config-->config.json and change
"externals": {
"jquery": "https://code.jquery.com/jquery-3.1.0.min.js",
"OwlCarousel":{
"path":"./node_modules/react-owl-carousel/lib/OwlCarousel.min.js",
"globalName":"OwlCarousel"
},
"Slider":{"path":"./node_modules/react-slick/lib/slider.js",
"globalName":"Sliders"}
},
SECOND:: npm install #types/youtube-api-search --save
THIRD ::
`npm install typings`
`typings install dt~youtube-api-search -global --save`
sometimes dt~ is neccessary sometimes it is not necessaary

Resources