CSSTransition not working with React Portals - reactjs

On this StackBlitz: https://stackblitz.com/edit/csstransition-test
I have a project that open a green div with a zoom-in effect:
/src/App.js
import React, { useState } from 'react';
import './style.css';
import Modal from './Modal';
export default function App() {
const [ isOpen, setIsOpen ] = useState(false);
const handleClick = () => {
setIsOpen(!isOpen);
};
return (
<div>
<h1>Hello StackBlitz!</h1>
<p>Start editing to see some magic happen :)</p>
<button onClick={handleClick}>Click Me</button>
<br /><br />
<Modal isOpen={isOpen}>
<div>Hello World</div>
</Modal>
</div>
);
}
/src/Portal.js
import { Component } from 'react';
import ReactDOM from 'react-dom';
const portal = document.getElementById('portal');
export default class Portal extends Component {
render() {
return ReactDOM.createPortal(this.props.children, portal);
}
}
/src/Modal.jsx
import React, { useRef } from "react";
import { CSSTransition } from "react-transition-group";
import Portal from "./Portal";
export default function Modal({ isOpen, children }) {
const container = useRef(null);
return (
<CSSTransition
nodeRef={container}
in={isOpen}
timeout={300}
classNames="modal"
unmountOnExit
onEnter={ () => console.log('entered') }
onExited={ () => console.log('exited') }
>
<div ref={container} style={{
display: 'inline-block',
backgroundColor: '#0f0',
padding: '50px',
}}>
{children}
</div>
</CSSTransition>
);
}
/src/style.css
h1,
p {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.modal-enter {
transform: scale(0);
}
.modal-enter-active {
transform: scale(1);
transition: transform 300ms;
}
.modal-exit {
transform: scale(1);
}
.modal-exit-active {
transform: scale(0);
transition: transform 300ms;
}
My problem is: I need to make it work with Portals.
On file: /src/Modal.jsx, if I replace the div inside: CSSTransition with: Portal then I get errors.
This is the code with the change:
/src/Modal.jsx
import React, { useRef } from "react";
import { CSSTransition } from "react-transition-group";
import Portal from "./Portal";
export default function Modal({ isOpen, children }) {
const container = useRef(null);
return (
<CSSTransition
nodeRef={container}
in={isOpen}
timeout={300}
classNames="modal"
unmountOnExit
onEnter={ () => console.log('entered') }
onExited={ () => console.log('exited') }
>
<Portal ref={container} style={{
display: 'inline-block',
backgroundColor: '#0f0',
padding: '50px',
}}>
{children}
</Portal>
</CSSTransition>
);
}
Please try the StackBlitz: https://stackblitz.com/edit/csstransition-test and you are also welcomed to post your own forked StackBlitz with the fixes.
Thanks!

I think this is happing because CSSTransition component is being created in root element. And the model is created in your portal element. This CSSTransition component is not wrapping anything.
You should instead wrap the whole Model with the portal, like this:
<Portal>
<CSSTransition
nodeRef={container}
in={isOpen}
timeout={300}
classNames="modal"
unmountOnExit
onEnter={ () => console.log('entered') }
onExited={ () => console.log('exited') }
>
<div ref={container} style={{
display: 'inline-block',
backgroundColor: '#0f0',
padding: '50px',
}}>
{children}
</div>
</CSSTransition>
</Portal>
I hope this helps.

Related

Toggling button image in React

I'm trying to toggle an icon in a button in react but I've tried everything and nothing works. I can change the background/text color toggling onClick but I'm missing something to change the icon and I don't know what! Any help?
Here's my code:
App.js
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { useState } from "react";
import Layout from "./layout";
import ThemeContext, { themes } from "./theme-context";
import { faSun, faMoon } from '#fortawesome/free-solid-svg-icons'
function App() {
const sun = <FontAwesomeIcon icon={faSun} />
const moon = <FontAwesomeIcon icon={faMoon} />
const [theme, setTheme] = useState(themes.dark)
const toggleTheme = () => theme === themes.dark ? setTheme(themes.light) : setTheme(themes.dark)
return (
<ThemeContext.Provider value={theme}>
<button onClick={toggleTheme}>
{sun}
</button>
<Layout />
</ThemeContext.Provider>
);
}
export default App;
theme-context.js
import React from "react"
export const themes = {
dark: {
color: "white",
background: "black",
padding: "5px",
width: "200px",
textAlign: "center",
},
light: {
color: "black",
background: "white",
padding: "5px",
width: "200px",
textAlign: "center",
}
}
const ThemeContext = React.createContext(themes.dark)
export default ThemeContext;
layout.jsx
import React, { useContext } from "react";
import ThemeContext from "./theme-context";
const Layout = () =>{
const theme = useContext(ThemeContext)
return (
<div style={theme} >
<p>This is your content</p>
</div>
)
}
export default Layout;
I have tried {themes.dark? : {sun} ? {moon}} but it didn't work.
The {themes.dark? : {sun} ? {moon}} was very close to correct (concept-wise, the syntax is not correct though). What you needed to do instead is { theme === themes.dark ? sun : moon } With your original snippet, you were just checking to see if themes.dark was truthy, which will always return true because it is an object. What you needed to do was check to see if the current theme was the same as themes.dark.
Hope this helps.

CSSTransition from react-transition-group not applying classes

I'm trying to integrate CSSTransition to my Gatsby site, but it is not applying any of the classes. I'm utilizing CSS modules, and I've got a <div> that serves as the parent that fades in and out, essentially applying the fade effect to this and covering the content while it changes. It's got the class fadEffect. Here is my app-layout component, and the SASS.
AppLayout.tsx
import React, { ReactNode, useState } from 'react';
import { ApiContext } from 'contexts/ApiContext';
import { graphql, StaticQuery } from 'gatsby';
import { TransitionGroup, CSSTransition } from 'react-transition-group';
import { Devtools } from '../devtools/Devtools';
import { Footer } from '../footer/Footer';
import { Header } from '../header/Header';
import s from './AppLayout.scss';
interface AppLayoutProps {
children: ReactNode;
location: string;
}
const isDev = process.env.NODE_ENV === 'development';
// tslint:disable no-default-export
export default ({ children, location }: AppLayoutProps) => {
const [fadeEffectVisible, setFadeEffectVisible] = useState(false);
const handleFadeEffectEntered = () => {
setTimeout(() => {
setFadeEffectVisible(false);
}, 50);
};
return (
<StaticQuery
query={`${NavQuery}`}
render={(data) => (
<>
<ApiContext>
<Header navigationContent={data.prismic.allNavigations.edges[0].node} />
<CSSTransition
in={fadeEffectVisible}
timeout={150}
classNames={{
enter: s.fadeEffectEnter,
enterActive: s.fadeEffectEnterActive,
enterDone: s.fadeEffectEnterDone,
exit: s.fadeEffectExit,
exitActive: s.fadeEffectExitActive,
}}
onEntered={handleFadeEffectEntered}
>
<div className={s.fadeEffect} aria-hidden="true" />
</CSSTransition>
<TransitionGroup component={null}>
<CSSTransition
key={location}
timeout={150}
classNames={{
enter: s.pageEnter,
}}
>
<div className={s.layout}>
{children}
<Footer navigationItems={data.prismic.allNavigations.edges[0].node} />
{isDev && <Devtools />}
</div>
</CSSTransition>
</TransitionGroup>
</ApiContext>
</>
)}
/>
);
};
const NavQuery = graphql`
query NavQuery {
prismic {
allNavigations {
edges {
node {
...NotificationBar
...NavigationItems
...FooterNavigationItems
}
}
}
}
}
`;
AppLayout.scss
#import '~styles/config';
:global {
#import '~styles/base';
}
.layout {
display: block;
min-height: 100vh;
}
.pageEnter {
display: none;
}
.fadeEffect {
display: none;
position: fixed;
z-index: 9;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #fff;
transition: opacity 0.15s linear;
&Enter {
display: block;
opacity: 0;
}
&Active,
&Done,
&Exit {
display: block;
opacity: 1;
}
&ExitActive {
opacity: 0;
}
}
I'm happy to provide more details/code if this isn't enough. I'm newish to React and Gatsby, so I'm still learning the lingo. Thanks in advance.
I don't see part of your code where you are updating fadeEffectVisible to true for first CSSTransition and I don't see in property at all on second CSSTransition and I would bet that is your issue. Please take a look at this example from React Transition Group for understanding usage of properties.
App.js
function App() {
const [inProp, setInProp] = useState(false);
return (
<div>
<CSSTransition in={inProp} timeout={200} classNames="my-node">
<div>
{"I'll receive my-node-* classes"}
</div>
</CSSTransition>
<button type="button" onClick={() => setInProp(true)}>
Click to Enter
</button>
</div>
);
}
Style.css
.my-node-enter {
opacity: 0;
}
.my-node-enter-active {
opacity: 1;
transition: opacity 200ms;
}
.my-node-exit {
opacity: 1;
}
.my-node-exit-active {
opacity: 0;
transition: opacity 200ms;
}
When the in prop is set to true, the child component will first receive the class example-enter, then the example-enter-active will be added in the next tick.

Full screen drag and drop files in React

In this official example of react-dropzone, a full screen drop zone is achieved by wrapping the whole app inside the <Dropzone /> component. I am creating a multi route app and feel that wrapping everything inside the <Dropzone /> component is not a very clean solution.
Is there a way to create a full screen/page drop zone in React without placing the <Dropzone /> component on the root level?
Create a route to a Dropzone form and adjust the height and size of the field by utilizing CSS.
Working example: https://codesandbox.io/s/l77212orwz (this example uses Redux Form, but you don't have to)
container/UploadForm.js
import React, { Component } from "react";
import { reduxForm } from "redux-form";
import ShowForm from "../components/showForm";
class UploadImageForm extends Component {
state = { imageFile: [] };
handleFormSubmit = formProps => {
const fd = new FormData();
fd.append("imageFile", formProps.imageToUpload[0]);
// append any additional Redux form fields
// create an AJAX request here with the created formData
};
handleOnDrop = newImageFile => this.setState({ imageFile: newImageFile });
resetForm = () => {
this.setState({ imageFile: [] });
this.props.reset();
};
render = () => (
<div style={{ padding: 10 }}>
<ShowForm
handleOnDrop={this.handleOnDrop}
resetForm={this.resetForm}
handleFormSubmit={this.handleFormSubmit}
{...this.props}
{...this.state}
/>
</div>
);
}
export default reduxForm({ form: "UploadImageForm" })(UploadImageForm);
components/showForm.js
import isEmpty from "lodash/isEmpty";
import React from "react";
import { Form, Field } from "redux-form";
import DropZoneField from "./dropzoneField";
const imageIsRequired = value => (isEmpty(value) ? "Required" : undefined);
export default ({
handleFormSubmit,
handleOnDrop,
handleSubmit,
imageFile,
pristine,
resetForm,
submitting
}) => (
<Form onSubmit={handleSubmit(handleFormSubmit)}>
<Field
name="imageToUpload"
component={DropZoneField}
type="file"
imagefile={imageFile}
handleOnDrop={handleOnDrop}
validate={[imageIsRequired]}
/>
<button
type="submit"
className="uk-button uk-button-primary uk-button-large"
disabled={submitting}
>
Submit
</button>
<button
type="button"
className="uk-button uk-button-default uk-button-large"
disabled={pristine || submitting}
onClick={resetForm}
style={{ float: "right" }}
>
Clear
</button>
</Form>
);
components/dropzoneField.js
import React, { Fragment } from "react";
import DropZone from "react-dropzone";
import { MdCloudUpload } from "react-icons/md";
import RenderImagePreview from "./renderImagePreview";
export default ({
handleOnDrop,
input,
imagefile,
meta: { error, touched }
}) => (
<div>
<DropZone
accept="image/jpeg, image/png, image/gif, image/bmp"
className="upload-container"
onDrop={handleOnDrop}
onChange={file => input.onChange(file)}
>
<div className="dropzone-container">
<div className="dropzone-area">
{imagefile && imagefile.length > 0 ? (
<RenderImagePreview imagefile={imagefile} />
) : (
<Fragment>
<MdCloudUpload style={{ fontSize: 100, marginBottom: 0 }} />
<p>Click or drag image file to this area to upload.</p>
</Fragment>
)}
</div>
</div>
</DropZone>
{touched && error && <div style={{ color: "red" }}>{error}</div>}
</div>
);
components/renderImagePreview.js
import map from "lodash/map";
import React from "react";
export default ({ imagefile }) =>
map(imagefile, ({ name, preview, size }) => (
<ul key={name}>
<li>
<img src={preview} alt={name} />
</li>
<li style={{ textAlign: "center" }} key="imageDetails">
{name} - {size} bytes
</li>
</ul>
));
styles.css
.dropzone-container {
text-align: center;
background-color: #efebeb;
height: 100%;
width: 100%;
}
.dropzone-area {
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.upload-container {
height: 100vh;
width: 100%;
margin-bottom: 10px;
}
ul {
list-style-type: none;
}
p {
margin-top: 0;
}

How can I deploy AppBar Material UI?

Im new in React Material UI and I am trying to deploy AppBar but i do not know how can I include childs into this NavBar. I want deploy AppBar when I click on the three left lines menu. My .jsx is:
import React from 'react';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import FlatButton from 'material-ui/FlatButton';
const STYLES = {
title: {
cursor: 'pointer',
},
titleStyle: {
textAlign: 'center'
},
buttonStyle: {
backgroundColor: 'transparent',
color: 'white'
}
};
const rightButtons = (
<div>
<FlatButton label="About" style={STYLES.buttonStyle} />
<FlatButton label="Home" style={STYLES.buttonStyle} />
</div>
);
export default class MenuAlumno extends React.Component {
constructor() {
super();
this.state = {
abierto:false
}
}
handleTouchTap = () => {
//alert('Has clickado sobre el título');
/*
console.log(this.state.abierto)
this.setState({
abierto:true
});
*/
console.log(this.state.abierto)
this.state.abierto = true;
console.log(this.state.abierto)
}
render() {
return (
<AppBar
title={<span style={STYLES.title}>- PLATAFORMA DE INCIDENCIAS -
</span>}
onTitleTouchTap={this.handleTouchTap}
titleStyle={STYLES.titleStyle}
iconClassNameRight="muidocs-icon-navigation-expand-more"
iconElementLeft={rightButtons}
>
</AppBar>
);
}
}
But this code replaces the 3 left lines for FlatButtons.
I want that when I click on the MenuButtonLeft a side menu deploy with the pages that contain my website (home, about us, contact,...). With the code I put before only shows the MenuButtonLeft and a Title into a Toolbar, but it does not do any action, it does not deploy any menu with the href to my others pages in my website.
Thank you.
Use the following code.
import React from 'react';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import FlatButton from 'material-ui/FlatButton';
import Drawer from 'material-ui/Drawer';
const STYLES = {
title: {
cursor: 'pointer',
},
titleStyle: {
textAlign: 'center'
},
buttonStyle: {
backgroundColor: 'transparent',
color: 'white'
}
};
const rightButtons = (
<div>
<FlatButton label="About" style={STYLES.buttonStyle} />
<FlatButton label="Home" style={STYLES.buttonStyle} />
</div>
);
export default class MenuAlumno extends React.Component {
constructor() {
super();
this.state = {
abierto:false
}
}
handleTouchTap = () => {
//alert('Has clickado sobre el título');
/*
console.log(this.state.abierto)
this.setState({
abierto:true
});
*/
console.log(this.state.abierto)
this.state.abierto = true;
console.log(this.state.abierto)
}
render() {
return (
<div>
<AppBar
title={<span style={STYLES.title}>- PLATAFORMA DE INCIDENCIAS -
</span>}
onTitleTouchTap={this.handleTouchTap}
titleStyle={STYLES.titleStyle}
iconClassNameRight="muidocs-icon-navigation-expand-more"
>
</AppBar>
<Drawer docked={false} width={200} open={this.state.abierto} >
{rightButtons}
</Drawer>
</div>
);
}
}
I resolve the problem above! Here is the solution:
import React from 'react';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import IconButton from 'material-ui/IconButton';
import NavigationMenu from 'material-ui/svg-icons/navigation/menu';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
/*
import IconButton from 'material-ui/IconButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import FlatButton from 'material-ui/FlatButton';
*/
const STYLES = {
title: {
cursor: 'pointer'
},
titleStyle: {
textAlign: 'center'
},
displayMenuTrue: {
position: 'relative'
},
displayMenuFalse: {
display: 'none'
},
contentStyle: {
transition: 'margin-left 450ms cubic-bezier(0.23, 1, 0.32, 1)',
marginLeft: '0px',
top: '0px'
},
contentStyleActive: {
marginLeft: '256px',
position: 'relative',
top: '-144px'
}
};
export default class MenuAlumno extends React.Component {
constructor() {
super();
this.state = {
drawerOpen:false
}
}
handleTouchTap = () => {
//alert('Has clickado sobre el título');
/*
console.log(this.state.abierto)
this.setState({
abierto:true
});
*/
console.log(this.state.drawerOpen)
this.state.drawerOpen = true;
console.log(this.state.drawerOpen)
}
controlMenu = () => {
if (this.state.drawerOpen) {
console.log(this.state.drawerOpen)
this.setState({
drawerOpen: false
});
$('.contenedor').css(STYLES.contentStyle);
} else {
console.log(this.state.drawerOpen)
this.setState({
drawerOpen: true
});
$('.contenedor').css(STYLES.contentStyle).css(STYLES.contentStyleActive);
}
}
render() {
return (
<div>
<AppBar
title={<span style={STYLES.title}>- PLATAFORMA DE
INCIDENCIAS -</span>}
onTitleTouchTap={this.handleTouchTap}
titleStyle={STYLES.titleStyle}
iconElementLeft={this.state.drawerOpen ? <IconButton>
<NavigationClose/></IconButton> : <IconButton><NavigationMenu/></IconButton>}
onLeftIconButtonTouchTap={this.controlMenu}
/>
<Drawer
open={this.state.drawerOpen}
containerStyle={this.state.drawerOpen ?
STYLES.displayMenuTrue : STYLES.displayMenuFalse}
>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item</MenuItem>
<MenuItem>Menu Item</MenuItem>
</Drawer>
</div>
);
}
}

React PDF viewer component rerenders constantly

I am using a React PDF viewer in my project. I have a react mui dialog component that I use with react draggable to drag it around.
import React from "react";
import withStyles from "#material-ui/core/styles/withStyles";
import makeStyles from "#material-ui/core/styles/makeStyles";
import DialogContent from "#material-ui/core/DialogContent";
import IconButton from "#material-ui/core/IconButton";
import ClearIcon from "#material-ui/icons/Clear";
import Draggable from "react-draggable";
import Paper from "#material-ui/core/Paper";
import Dialog from "#material-ui/core/Dialog";
import PDFViewer from "./PDFViewer";
function PaperComponent({...props}) {
return (
<Draggable
>
<Paper {...props} />
</Draggable>
);
}
const StyledDialog = withStyles({
root: {
pointerEvents: "none"
},
paper: {
pointerEvents: "auto"
},
scrollPaper: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
marginRight: 20
}
})(props => <Dialog hideBackdrop {...props} />);
const useStyles = makeStyles({
dialog: {
cursor: 'move'
},
dialogContent: {
'&:first-child': {
padding: 10,
background: 'white'
}
},
clearIcon: {
position: 'absolute',
top: -20,
right: -20,
background: 'white',
zIndex: 1,
'&:hover': {
background: 'white'
}
},
paper: {
overflowY: 'visible',
maxWidth: 'none',
maxHeight: 'none',
width: 550,
height: 730
}
});
const PDFModal = (props) => {
const classes = useStyles();
const {open, onClose, pdfURL} = props;
return (
<StyledDialog
open={open}
classes={{root: classes.dialog, paper: classes.paper}}
PaperComponent={PaperComponent}
aria-labelledby="draggable-dialog"
>
<DialogContent classes={{root: classes.dialogContent}} id="draggable-dialog">
<IconButton className={classes.clearIcon} aria-label="Clear" onClick={onClose}>
<ClearIcon/>
</IconButton>
<PDFViewer
url={pdfURL}
/>
</DialogContent>
</StyledDialog>
);
};
export default PDFModal;
And this is the PDFViewer component:
import React from 'react';
import { Viewer, SpecialZoomLevel, Worker } from '#react-pdf-viewer/core';
import { defaultLayoutPlugin } from '#react-pdf-viewer/default-layout';
import '#react-pdf-viewer/core/lib/styles/index.css';
import '#react-pdf-viewer/default-layout/lib/styles/index.css';
import ArrowForward from "#material-ui/icons/ArrowForward";
import ArrowBack from "#material-ui/icons/ArrowBack";
import Button from "#material-ui/core/Button";
import IconButton from "#material-ui/core/IconButton";
import RemoveCircleOutlineIcon from '#material-ui/icons/RemoveCircleOutline';
import AddCircleOutlineIcon from '#material-ui/icons/AddCircleOutline';
import './PDFViewer.css';
const PDFViewer = ({url}) => {
const renderToolbar = (Toolbar) => (
<Toolbar>
{
(slots) => {
const {
CurrentPageLabel, CurrentScale, GoToNextPage, GoToPreviousPage, ZoomIn, ZoomOut,
} = slots;
return (
<div
style={{
alignItems: 'center',
display: 'flex',
}}
>
<div style={{ padding: '0px 2px' }}>
<ZoomOut>
{
(props) => (
<IconButton aria-label="delete" onClick={props.onClick}>
<RemoveCircleOutlineIcon />
</IconButton>
)
}
</ZoomOut>
</div>
<div style={{ padding: '0px 2px' }}>
<CurrentScale>
{
(props) => (
<span>{`${Math.round(props.scale * 100)}%`}</span>
)
}
</CurrentScale>
</div>
<div style={{ padding: '0px 2px' }}>
<ZoomIn>
{
(props) => (
<IconButton aria-label="delete" onClick={props.onClick}>
<AddCircleOutlineIcon />
</IconButton>
)
}
</ZoomIn>
</div>
<div style={{ padding: '0px 2px', marginLeft: 'auto' }}>
<GoToPreviousPage>
{
(props) => (
<Button
style={{
cursor: props.isDisabled ? 'not-allowed' : 'pointer',
height: '30px',
width: '30px'
}}
disabled={props.isDisabled}
disableElevation
disableFocusRipple
onClick={props.onClick}
variant="outlined">
<ArrowBack fontSize="small"/>
</Button>
)
}
</GoToPreviousPage>
</div>
<div style={{ padding: '0px 2px' }}>
<CurrentPageLabel>
{
(props) => (
<span>{`${props.currentPage + 1} av ${props.numberOfPages}`}</span>
)
}
</CurrentPageLabel>
</div>
<div style={{ padding: '0px 2px' }}>
<GoToNextPage>
{
(props) => (
<Button
style={{
cursor: props.isDisabled ? 'not-allowed' : 'pointer',
height: '30px',
width: '30px'
}}
disabled={props.isDisabled}
disableElevation
disableFocusRipple
onClick={props.onClick}
variant="outlined">
<ArrowForward fontSize="small"/>
</Button>
)
}
</GoToNextPage>
</div>
</div>
)
}
}
</Toolbar>
);
const defaultLayoutPluginInstance = defaultLayoutPlugin({
renderToolbar,
sidebarTabs: defaultTabs => [defaultTabs[1]]
});
// constantly called
console.log('entered')
return (
<div
style={{
height: '100%',
}}
>
<Worker workerUrl="https://unpkg.com/pdfjs-dist#2.5.207/build/pdf.worker.min.js">
<Viewer
fileUrl={url}
defaultScale={SpecialZoomLevel.PageFit}
plugins={[
defaultLayoutPluginInstance
]}
/>
</Worker>
</div>
);
};
export default PDFViewer;
I can see in the console that PDFViewer is being constantly called. I am not sure what is causing this rerenders the whole time?
Isn't it make sense to re-render when you have a new fileUrl passed to PDFModal? The following sequence should be how the app is executed.
PDFModal, PDFViewer and other related components init
When a file is dragged into the PaperComponent context, the upper level component handles it and passing pdfURL as props
const PDFModal = (props) => {
const { ......., pdfURL } = props;
//...skipped code
return (
<StyledDialog
PaperComponent={PaperComponent}
>
//...skipped code
<PDFViewer
url={pdfURL}
/>
</StyledDialog>
);
};
PDFViewer updated because there is a new prop.
const PDFViewer = ({ url }) => {
//...skipped code
return (
//...skipped code
<Viewer
fileUrl={url}
/>
);
}
I agree what #LindaPaiste said, putting Toolbar maybe an option since it doesn't use the url props passed in. For the re-render problem, I suggest that useCallback can be used to wrap the whole PDFViewer component. Only update the component when the url has changed.
This link provide some insights on when to use useCallback which can be a reference.
const PDFViewer = useCallback(
({ url }) => {
//...skipped code
return (
//...skipped code
<Viewer
fileUrl={url}
/>
)
}, [url])

Resources