I am trying to display pdf using react-pdf in create-react-app application.
I followed the instructions but the pdf is not displayed.
import { makeStyles, Box, Grid } from "#material-ui/core";
import React, { useState } from "react";
import Header from "./header";
import contractPdf from "../../sample.pdf";
import { Document, Page } from "react-pdf";
const useStyles = makeStyles((theme) => ({
root: {
padding: "32px 24px 14px 24px",
},
pdfArea: {
borderRight: "1px solid #DDDDDD",
height: "calc(100vh - 195px)",
},
}));
const BasicComponent = (props) => {
const classes = useStyles();
const [numPages, setNumPages] = useState(null);
const [pageNumber, setPageNumber] = useState(1);
function onDocumentLoadSuccess({ numPages: nextNumPages }) {
setNumPages(nextNumPages);
}
return (
<Box className={classes.root}>
<Header />
<Grid container>
<Grid item xs={8}>
<Box className={classes.pdfArea}>
<Document
file={contractPdf}
onLoadSuccess={onDocumentLoadSuccess}
options={options}
>
<Page pageNumber={1} />
</Document>
</Box>
</Grid>
<Grid item xs={4}>
<Box className={classes.inputArea}>User input</Box>
</Grid>
</Grid>
</Box>
);
};
export default BasicComponent;
I checked the debug in development mode and it shows Uncaught SyntaxError: Unexpected token '<' in pdf.worker.js
Can anyone help me?
I appreciate your help. Thank you
I wasted so much time that I decided to write an answer to this question to help anybody in my situation avoid the waste of time. The instructions as described in the github site for react-pdf do not work with react 17.02 CRA 5 and Webpack 5.6.6 regarding the pdf.worker.js worker.
As the site indicates without giving a clear solution,
import { Document, Page } from 'react-pdf/dist/esm/entry.webpack5';
creates a heap out of memory error during compilation that is not fixed even by allocating 8 gigabytes of memory.
Using the standard instructions doesn't work either, creating an error that is dependent of the last web directory that was used in your react-router routes. This creates a weird bug, because sometimes it works and sometimes it doesn't.
The standard instructions say:
that you should add:
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.js';
when using the .min file, instead of the regular .js file, that gave me the idea of adding the following:
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';
But it didn't work either. To make it work I had to do the following:
copy pdf.worker.js and pdf.worker.js.map from pdfjs-dist/legacy/build to public directory (it also works if you copy from the build - not legacy directory)
and,
add to my code the following:
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.js';
Yes, the '/' did it. Otherwise it'd go back to load my index.html from my /public directory.
As per documentation you have to add this line in your code.(react-pdf)
import { pdfjs } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;
Related
Im trying to make a header in NextJS but this keeps happenning:
I tried to use 100% width, 100% height.
My code:
import type { NextPage } from 'next';
import { Fragment } from 'react';
import Header from '../../components/Header';
const Home: NextPage = () => {
return (
<Fragment>
<Header />
<div>Home</div>
</Fragment>
);
};
export default Home;
The header component(its a div with background color black):
import { Container } from './styled';
const Header = () => {
return <Container>HEADER</Container>;
};
export default Header;
From your code looks like there are 2 possible ways that this can go wrong.
Scenario #01:
Check if there's some global style rules with matching styles i.e background:black in your globals.css (located in styles folder)
Scenario #02
You have the following container being imported in your component.
import { Container } from './styled';
Try commenting this out and then wrap the content in a fragment i.e
<Fragment> HEADER </Fragment>
If this solves the issue of black-background then it means there's something wrong about the container component imported.
Based on the screenshot of the devtools it looks like there's a 8px margin on the background for some reason.
Look in your CSS files if you have any rules that do that.
If this isn't from you, override it by adding a rule in your css like
body {
margin: 0;
}
I just finished coding a website with a Virtual Tour made on Unity, i've exported it as WEBGL with compression format disabled, and decompression fallback off(Unity). Then added this to my code on React
import React from "react";
import Unity, { UnityContext } from "react-unity-webgl";
const unityContext = new UnityContext({
loaderUrl: "../Build/unity341.loader.js",
dataUrl: "../Build/unity341.data",
frameworkUrl: "../Build/unity.framework.js",
codeUrl: "../Build/unity341.wasm",
});
function Game() {
return <Unity unityContext={unityContext} />;
}
export default Game;
then imported the game on the page
import React, {Component} from 'react';
import Game from './game.jsx';
import {Container} from 'react-bootstrap';
class GamePage extends Component {
render() {
return (
<div>
<Game/>
<Container>
//text and stuff inside the container
</Container>
</div>
);
}
}
export default GamePage;
But when i render it on my localhost i dont get the Unity viewer, and when inspecting on Chrome the only thing i see where the game should be is the following tag
<canvas class>
Thanks for your help guys !
Put generated WebGL files from Build folder to public folder in react. See picture. Those files must be in public folder because react server is hosting static files in this folder. For example i have put them to public\build folder. See picture.
Code in react:
const unityContext = new UnityContext({
loaderUrl: 'build/<AppName>.loader.js',
dataUrl: 'build/<AppName>.data',
frameworkUrl: 'build/<AppName>.framework.js',
codeUrl: 'build/<AppName>.wasm',
});
<Unity unityContext={unityContext} style={{ width: '100%', height: '100%' }} />
I've looked into code prettifiers like google-code-prettify, beautify, etc. Unfortunately, I haven't been able to get any of these to work in my React app. I am currently using react-ace to display dynamically populated code snippets, but they are only color-highlighted, not formatted.
Are there any simple examples of some way that I can get this to work in a React App? It doesn't have to be using Ace editor - that was sort of my hack to get the code displayed somewhat nicely.
Thanks for this question, you can use prettier to format the code. You may need to configure different parser based on the language or framework you are using.
Here is a sample codesandbox for formatting JS code. Link: https://codesandbox.io/s/currying-architecture-tm785?file=/src/App.js
Code for the main file:
import React from "react";
import prettier from "prettier/standalone";
import babylon from "prettier/parser-babel";
import "./styles.css";
export default function App() {
const [code, setCode] = React.useState(`
const a = "abc";
const b = 'a'
console.log(a);
`);
const formatCode = () => {
const formattedCode = prettier.format(code, {
parser: "babel",
plugins: [babylon]
});
setCode(formattedCode);
};
return (
<div className="App">
<textarea
style={{ height: "100px", width: "100%", display: "block" }}
value={code}
/>
<button onClick={formatCode}>Format Code with Prettier</button>
</div>
);
}
Hope this helps!
I want to get pdf file from my GCP , but I get CORS error. Ok , np . I've tried to find how to solve this issue in GCP . Found this example :
https://bitmovin.zendesk.com/hc/en-us/articles/360000059353-How-do-I-set-up-CORS-for-my-Google-Cloud-Storage-Bucket-
I've following all of this instructions :
echo '[{"origin": ["*"],"responseHeader": ["Content-Type"],"method": ["GET", "HEAD"],"maxAgeSeconds": 3600}]' > cors-config.json
gsutil cors set cors-config.json gs://booknote-pdf-files-store
import React, { useState } from 'react'
import { Document, Page } from 'react-pdf'
import { withStyles } from '#material-ui/styles'
import PropTypes from 'prop-types'
import CircularProgress from '#material-ui/core/CircularProgress'
import styles from './styles'
const Application = ({ classes }) => {
const [numPages, setNumPages] = useState(null)
const [pageNumber, setPageNumber] = useState(1)
const onDocumentLoadSuccess = ({ numPages }) => {
setNumPages(numPages)
}
return (
<div className={classes.container}>
<Document
file="https://storage.cloud.google.com/booknote-pdf-files-store/living_in_the_light.pdf"
onLoadSuccess={onDocumentLoadSuccess}
renderMode="svg"
loading={<CircularProgress />}>
<Page pageNumber={pageNumber} />
</Document>
</div>
)
}
Application.propTypes = {
classes: PropTypes.instanceOf(Object).isRequired,
}
But i still get CORS error. What am I doing wrong ? If you need additional info , pls let me know
Also you can check npm package which I use for this purpose :
https://www.npmjs.com/package/react-pdf
Assuming that the gsutil command for setting up cors actually worked ( I'd double-check just to be sure, run: gsutil cors get gs://booknote-pdf-files-store and see if the changes have been reflected ). Simply put, react-pdf relies a lot on PDF.js and so it is possible that this is caused by how PDF.js gets the file from the server.
Taken straight from PDF.js FAQ, "PDF.js runs with the same permissions as any other JavaScript code, which means it cannot do cross origin requests".
There are a few workarounds available at your disposal though, one of them is using a proxy that return the Access-Control-Allow-Origin header if it's not at the Same Origin. Thus, your request for the file will not be sent to GCS but will be made to your proxy which will forward them to GCS. I highly giving PDF.js' FAQ a read, surely it will point you in the right direction.
I'm trying to add Fontawesome pro to my react app.
I've tried almost all of the options on the getting started tab for Font Awesome - and all that is producing is the free brands. So - now I have a mash up of attempts and and currently stuck on following the instructions set out by clodal in this post
I have a package.json with the following dependencies:
"#fortawesome/fontawesome-svg-core": "^1.2.8",
"#fortawesome/pro-light-svg-icons": "^5.5.0",
"#fortawesome/free-solid-svg-icons": "^5.5.0",
"#fortawesome/pro-regular-svg-icons": "^5.5.0",
"#fortawesome/pro-solid-svg-icons": "^5.5.0",
"#fortawesome/react-fontawesome": "^0.1.3",
I have seen this post and note others are struggling to figure out how to get started with font awesome.
I have added global config auth token to my app.
I have read the upgrading instructions here.
Currently - i'm getting an error that says:
Error: Can't resolve '#fortawesome/pro-brands-svg-icons' in '/Users/18/src/routes/How/components/HowPage'
In that page, I have:
import React from 'react'
import PropTypes from 'prop-types'
import classes from './HowPage.scss'
import GridContainer from "components/Grid/GridContainer.jsx";
import GridItem from "components/Grid/GridItem.jsx";
import Clearfix from "components/Clearfix/Clearfix.jsx";
import { library } from '#fortawesome/fontawesome-svg-core'
import { fas } from '#fortawesome/pro-solid-svg-icons'
import { faTwitter } from '#fortawesome/pro-brands-svg-icons'
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
export const HowPage = ({ how }) => (
<div className={classes.container}>
<h1 style={headstyle}>How it Works</h1>
<GridContainer justify="center">
<GridItem
xs={12}
sm={8}
md={8}
className={`${classes.mlAuto} ${classes.mrAuto} ${
classes.textCenter
}`}
>
<span>
<i className="fas fa-layer-plus"></i>
</span>
<i className="fal fa-stroopwafel"></i>
<FontAwesomeIcon icon="coffee" />
<i className="fab fa-twitter" />
</GridItem>
</GridContainer>
<pre>{JSON.stringify(how, null, 2)}</pre>
</div>
)
HowPage.propTypes = {
how: PropTypes.object // from enhancer (firestoreConnect + connect)
}
export default HowPage
In my index.html I have:
<link href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" rel="stylesheet">
I have tried adding these import statements to the page on which Im trying to use the fonts (I can't understand the library building instructions).
That produces the errors (expected, given the next issue):
I don't know where to add the following library add call:
library.add(fas, faTwitter)
My app gets initialised via main.js. That page has:
import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import { initScripts } from 'utils'
import { version } from '../package.json'
import { env } from './config'
import './styles/core.scss'
// import { library } from '#fortawesome/fontawesome-svg-core'
// import { fal } from '#fortawesome/pro-light-svg-icons'
// Window Variables
// ------------------------------------
window.version = version
window.env = env
initScripts()
// Store Initialization
// ------------------------------------
const initialState = window.___INITIAL_STATE__ || {
firebase: { authError: null }
}
const store = createStore(initialState)
// Render Setup
// ------------------------------------
const MOUNT_NODE = document.getElementById('root')
let render = () => {
const App = require('./containers/App').default
const routes = require('./routes/index').default(store)
ReactDOM.render(<App store={store} routes={routes} />, MOUNT_NODE)
}
// Development Tools
// ------------------------------------
if (__DEV__) {
if (module.hot) {
const renderApp = render
const renderError = error => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
render = () => {
try {
renderApp()
} catch (e) {
console.error(e) // eslint-disable-line no-console
renderError(e)
}
}
// Setup hot module replacement
module.hot.accept(['./containers/App', './routes/index'], () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
)
}
}
// Let's Go!
// ------------------------------------
if (!__TEST__) render()
I think the instructions want me to write that library add call in there - but I can't understand how to do it.
I have seen this post - this user has figured out how to add code to the app.js file. I think I am stuck on this step. My app.js is in main.js - I don't know where to put the library call and I don't know whether this example means that the user will only have access to the 2 icons named in that post (faSpinnerThird, faCircle).
I am using Material-UI - and can see that it contemplates the use of font awesome icons. I just can't figure out how to set it up.
PS: the contributing guidelines on the GitHub support page ask for questions to be tagged with react-fontawesome. There isn't a tag for that reference - I don't have enough points to create one - maybe someone who does can sort that out.
For others struggling with FA in React - PKK's answer on this post helped me How to integrate FontAwesome 5 Pro with React?
However, it doesn't seem to work with 2 word icon names. But - at least it works for many icons. I always thought of FA as plug and play - this has been many hours in figuring out how to get it to work.
According to the "importing icons" documentation, there is no #fortawesome/pro-brands-svg-icons. There is only #fortawesome/free-brands-svg-icons.