React pdf js - Warning: Setting up fake worker - javascript

I am using a react pdf viewer and I would like to set up worker locally. I have tried doing that like this:
import pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";
<Worker workerUrl={pdfjsWorker}>
<Viewer
fileUrl={url}
defaultScale={SpecialZoomLevel.PageFit}
plugins={[
defaultLayoutPluginInstance
]}
/>
</Worker>
But, that throws a warning:
Warning: Setting up fake worker
What is the correct way of import a worker then, why do I get this warning?

I was facing similar issues resolved them by adding the pdf.worker.js
Git Refrence
I added the js file in the head for the worker.js i.e https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.js
Then I correct the version (2.10.377 to 2.3.200) as per the console error and it starts loading the pdf

In my case, instead of write the code like this:
<script src="/js/pdf.worker.min.js"></script>
<script src="/js/pdf.min.js"></script>
I wrote it as:
<!--script src="/js/pdf.worker.min.js"></script--> // removed
<script src="/js/pdf.min.js"></script>
$(function() {
pdfjsLib.GlobalWorkerOptions.workerSrc = '/js/pdf.worker.min.js';
});
Which made the warning disappear ...
even though my PDF was rendered anyway - i just wanted that warning removed.

Watch out!
pdfjs version must be the same
Use it like below please
import { Worker, Viewer } from '#react-pdf-viewer/core';
import '#react-pdf-viewer/core/lib/styles/index.css';
import { pdfjs } from 'react-pdf';
const YourComponent = () => {
return (
<div>
<Worker workerUrl={`https://unpkg.com/pdfjs-dist#${pdfjs.version}/build/pdf.worker.min.js`}>
<Viewer fileUrl={fileUrl} />
</Worker>
</div>
)
};

Worker component expects a workerUrl which is of type string. You might have to replace pdfjsWorker in your code with actual pdf-worker url.
const pdfVersion = "2.6.347"
const pdfWorkerUrl = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfVersion}/pdf.worker.js`
<Worker workerUrl={pdfWorkerUrl}>
<Viewer
fileUrl={url}
defaultScale={SpecialZoomLevel.PageFit}
plugins={[
defaultLayoutPluginInstance
]}
/>
</Worker>
Note: Please make sure to set the same version for both pdfjs-dist and worker.
The official documentation mentions the same thing here: https://react-pdf-viewer.dev/docs/basic-usage/

pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.0.279/pdf.worker.min.js'
Add this after you import pdfjs-dist and try matching the version(here 3.0.279) as per the console error. It worked for me.

Related

Fresh installation by npx react-native init myapp causes in problem warning

I do the terminalcommand npx react-native init myapp. Change the dir to /myapp and vs code shows me this problem warning:
There are some more Errors like this in the file, without doing anything.
What did I miss?
As discussed in the comments, this is a VSCode error only, since the application is using TypeScript annotations and the default file extension for typescript files is .ts. It could be solved by changing the file extension to .ts and possibly change occurrences of App.js in the project to App.ts.
However, this error message does not effect the runtime behavior. Since it might be desired to not change any code, we can get rid of the error message by changing the VSCode settings.
This is done by setting "javascript.validate.enable": false.
This is not an Error. It shows the return type of the Function you ca change it to.
const App = () => {
return(
<View>
</View>
)
}
Try this,
import { Text, View } from 'react-native'
import React from 'react'
export default function App() {
return (
<View>
<Text>hello world!</Text>
</View>
)
}

How to import lodash library in js file [duplicate]

I'd like to import this javascript package in React
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
However, there is no NPM package, so I can't import it as such:
import dwolla from 'dwolla'
or
import dwolla from 'https://cdn.dwolla.com/1/dwolla.js'
so whenver I try
dwolla.configure(...)
I get an error saying that dwolla is undefined. How do I solve this?
Thanks
Go to the index.html file and import the script
<script src="https://cdn.dwolla.com/1/dwolla.js"></script>
Then, in the file where dwolla is being imported, set it to a variable
const dwolla = window.dwolla;
This question is getting older, but I found a nice way to approach this using the react-helmet library which I feel is more idiomatic to the way React works. I used it today to solve a problem similar to your Dwolla question:
import React from "react";
import Helmet from "react-helmet";
export class ExampleComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
myExternalLib: null
};
this.handleScriptInject = this.handleScriptInject.bind(this);
}
handleScriptInject({ scriptTags }) {
if (scriptTags) {
const scriptTag = scriptTags[0];
scriptTag.onload = () => {
// I don't really like referencing window.
console.log(`myExternalLib loaded!`, window.myExternalLib);
this.setState({
myExternalLib: window.myExternalLib
});
};
}
}
render() {
return (<div>
{/* Load the myExternalLib.js library. */}
<Helmet
script={[{ src: "https://someexternaldomain.com/myExternalLib.js" }]}
// Helmet doesn't support `onload` in script objects so we have to hack in our own
onChangeClientState={(newState, addedTags) => this.handleScriptInject(addedTags)}
/>
<div>
{this.state.myExternalLib !== null
? "We can display any UI/whatever depending on myExternalLib without worrying about null references and race conditions."
: "myExternalLib is loading..."}
</div>
</div>);
}
}
The use of this.state means that React will automatically be watching the value of myExternalLib and update the DOM appropriately.
Credit: https://github.com/nfl/react-helmet/issues/146#issuecomment-271552211
for typescript developers
const newWindowObject = window as any; // cast it with any type
let pushNotification = newWindowObject.OneSignal; // now OneSignal object will be accessible in typescript without error
You can't require or import modules from a URL.
ES6: import module from URL
What you can do is make an HTTP request to get the script content & execute it, as in the answer for how to require from URL in Node.js
But this would be a bad solution since your code compilation would depend on an external HTTP call.
A good solution would be to download the file into your codebase and import it from there.
You could commit the file to git if the file doesn't change much & are allowed to do it. Otherwise, a build step could download the file.
var _loaded = {};
function addScript(url) {
if (!loaded[url]) {
var s = document.createElement('script');
s.src = url;
document.head.appendChild(s);
_loaded[url] = true;
}
}
how to load javascript file from cdn server in a component
Add the script tag in your index.html and if you are using Webpack, you can use this webpack plugin https://webpack.js.org/plugins/provide-plugin/

How to fetch files from CDN with NuxtJS content module?

I want to fetch files from another server (e.g. a CDN) with the #nuxtjs/content module so that the .md files can be managed independently without Nuxt.js.
My current nuxt.config.js file looks like this:
export default {
...
content: {
dir: 'http://some-cdn.xyz/content/'
},
...
}
Now I want to load the content in the pages/_slug.vue file:
<template>
<div>
<NuxtContent :document="doc" />
</div>
</template>
<script>
export default {
async asyncData({ $content, params }) {
const doc = await $content(params.slug || 'index').fetch();
return { doc };
},
};
</script>
Now when I type in http://localhost:3000/some-page, I should get the corresponding file (some-page.md) from the CDN. Instead, I get this error from Nuxt.js: /some-page not found.
What should I do to get it working and is this even possible with my current setup?
As told here: https://github.com/nuxt/content/issues/237
This is not doable with the content module and is not planned to be done neither. A solution would be to manually fetch the files during the build time or alike.
You can maybe get some inspiration from this comment: https://github.com/nuxt/content/issues/37#issuecomment-664331854 or use another markdown parser.
Since #nuxtjs/content can't fetch files from another server, I used the marked.js library instead.

Dynamically creating an element on which the react app mounts

I want to create a build of my javascript application using react which currently is just a single file defined as below. It does nothing but creates a div and keeps on changing the color of the hello-world text after it mounts.
import * as React from "react";
import * as ReactDOM from "react-dom";
class App extends React.Component {
componentDidMount() {
const colorBox = ["red","blue","green"];
const element = document.getElementById("my-div");
setInterval(() => {
element.style.color = colorBox[parseInt(Math.floor(Math.random() * colorBox.length))];
}, 3000);
}
render() {
return (
<div id={"my-div"}>
Hello, World.
</div>
);
}
}
ReactDOM.render(<App />,
document.body.appendChild(document.createElement("div")));
I am using parcel js as a bundler. I bundle my javascript as parcel build index.js and this creates a build of my javascript file inside dist folder. So far, so good. But the moment, I load this javascript using a script tag on my website as:
<script type="text/javascript" src="https://mycdn.com/bundle.index.js"></script>
It throws an error
index.js:16 Uncaught TypeError: Cannot read property 'appendChild' of null
at Object.parcelRequire.Focm.react (index.js:16)
at f (index.js:1)
at parcelRequire.YOwE (index.js:1)
at index.js:1
Why it cannot access appendChild of document.body? I also checked that document.body is null. What is happening here? What is it that I am missing?
First of all I'm not sure this is a great idea to have code in the bundle that directly affects the page like this.
My guess as to why this is happening is it has to do with when the bundle is loaded in the page. Is it in head? If so document.body may not be available.
It is probably best if you are going to do something like this to use the events associated with the document being ready.
This can get complicated depending on your needs, but if you have access to jQuery, you can use .ready().
If not you can use various vanilla js options.
I guess your problem is related to the bundle or you ask for an element before it is available because it is working fine here: https://jsfiddle.net/rL6dnhps
If you load it from the head, try to put at the end of the body in order to wait for the body to be ready or wrap it inside an IIFE like below:
(function() {
// the DOM will be available here
ReactDOM.render(<App />,
document.body.appendChild(document.createElement("div")));
})();

Next.js: How to dynamically import external client-side only React components into Server-Side-Rendering apps developed?

I know this question has been asked multiple times before but none of the solution seems to work.
I'm trying to use the library 'react-chat-popup' which only renders on client side in a SSR app.(built using next.js framework) The normal way to use this library is to call import {Chat} from 'react-chat-popup' and then render it directly as <Chat/>.
The solution I have found for SSR apps is to check if typedef of window !=== 'undefined' in the componentDidMount method before dynamically importing the library as importing the library normally alone would already cause the window is not defined error. So I found the link https://github.com/zeit/next.js/issues/2940 which suggested the following:
Chat = dynamic(import('react-chat-popup').then(m => {
const {Foo} = m;
Foo.__webpackChunkName = m.__webpackChunkName;
return Foo;
}));
However, my foo object becomes null when I do this. When I print out the m object in the callback, i get {"__webpackChunkName":"react_chat_popup_6445a148970fe64a2d707d15c41abb03"} How do I properly import the library and start using the <Chat/> element in this case?
Next js now has its own way of doing dynamic imports with no SSR.
import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(
() => import('../components/hello3'),
{ ssr: false }
)
Here is the link of their docs: next js
I've managed to resolve this by first declaring a variable at the top:
let Chat = ''
then doing the import this way in componentDidMount:
async componentDidMount(){
let result = await import('react-chat-popup')
Chat = result.Chat
this.setState({
appIsMounted: true
})
}
and finally render it like this:
<NoSSR>
{this.state.appIsMounted? <Chat/> : null}
</NoSSR>
You may not always want to include a module on server-side. For
example, when the module includes a library that only works in the
browser.
Import the library normally in child component and import that component dynamically on parent component.
https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr
This approach worked for me.

Categories