I am building a site with Gatsby.
I am using a component that imports a script and returns a form.
The problem is, that after you loaded the page that shows the form, and then you click to any other page and go back to that form page, the css fully crashes for the entire site and you have to refresh the whole page.
To check out what I mean click this link https://baerenherz.org/, go to the dark blue button on the very right of the menu, then click to any other navigation site and then click again on the blue button (jetzt-spenden).
Here is my component for the donation form :
import React, { useState, useEffect } from "react"
import {Helmet} from "react-helmet"
import Loading from "./Loading"
function Child() {
return(
<div style={{width: "75%", margin: "4em auto"}} >
<Helmet>
<script type='text/javascript' aysnc>
{` window.rnw.tamaro.runWidget('.dds-widget-container', {language: 'de'}) `}
</script>
</Helmet>
<div className="dds-widget-container"></div>
</div>
)
}
function RaiseNow() {
const [loaded, setLoaded] = useState(false)
useEffect(() => {
const scriptTag = document.createElement('script')
scriptTag.src='https://tamaro.raisenow.com/xxx/latest/widget.js'
scriptTag.addEventListener('load', ()=> setLoaded(true))
document.body.appendChild(scriptTag)
return ()=>{
scriptTag.removeEventListener(); // check if necessary
setLoaded(false) // check if necessary
}
}, []);
return (
<>
{loaded ? <Child /> : <Loading/>}
</>
)
}
export default RaiseNow
What I noticed is, that the second time you visit the page, the Loading.... component does not even show anymore.. the Layout is displayed but as soon as the form shows, it crashes...
Since I cannot solve this issue since literally last year I would really appreciate any help with this. Thank you in advance.
Apparently, your script is breaking React's hydration when the component should be mounted/unmounted. There's no "clean" solution if there's no React-based script available. The problem here is that your script is manipulating the DOM while React manages the virtual DOM (vDOM). Changes in the DOM outside React's scope are not listened to by React and vice versa.
That said, I'd try forcing the loading and rendering of your widget each time the page loads. Something like:
function RaiseNow() {
const [loaded, setLoaded] = useState(false)
useEffect(() => {
const scriptTag = document.createElement('script')
scriptTag.src='https://tamaro.raisenow.com/xxx/latest/widget.js'
scriptTag.addEventListener('load', ()=> setLoaded(true))
document.body.appendChild(scriptTag)
window.rnw.tamaro.runWidget('.dds-widget-container', {language: 'de'})
return ()=>{
scriptTag.removeEventListener('load', setLoaded(false)); // check if necessary
setLoaded(false) // check if necessary
}
}, []);
return (
<>
{loaded ? <Child /> : <Loading/>}
</>
)
}
export default RaiseNow
Without a CodeSandbox it's difficult to guess how the code will behave but what it's important is to detach and clean up the listeners when the component is removed from the UI to avoid breaking React's hydration process, in the return statement. From the useEffect docs:
The clean-up function runs before the component is removed from the UI
to prevent memory leaks. Additionally, if a component renders multiple
times (as they typically do), the previous effect is cleaned up before
executing the next effect. In our example, this means a new
subscription is created on every update. To avoid firing an effect on
every update, refer to the next section.
There, besides removing the listeners from the script, you can also set the loading state to false.
I've also removed the second useEffect because the idea to avoid the CSS breaking is to force the loading of the script in each page rendering. It's not an optimal solution but it may work for you. The ideal solution would be using React-based dependencies.
Another thing to take into account is to delay the trigger of your rnw.tamaro script until the DOM tree is loaded, by moving it from the Helmet to the useEffect. This should ensure that your div and the window are available.
Turns out it was a issue on their end. Since they did an update it works.
Related
In a chat app I am building I want to deduct credits from a user's account, whenever the users sends a message and when a chat is initiated.
The user account is accessible in the app as a context and uses a snapshot listener on a firestore document to update whenever something changes in the user account document. (See code samples 1. and 2. at the bottom)
Now whenever anything in the userAccount object changes, all of the context providers children (NavigationStructure and all its subcomponents) are re-rendered as per React's documentation.
This, however causes huge problems on the chat screen that also uses this context:
The states that are defined there get re-initalized whenever something in the context changes. For example, I have a flag that indicates whether a modal is visible, default value is visible. When I go onto the chat screen, hide the modal, change a value manually in the firestore database (e.g. deduct credits) the chat screen is rerendered and the modal is visible again. (See code sample 3.)
I am very lost what the best way to solve this issue is, any ideas?
Solutions that I have thought about:
Move the credits counter to a different firestore document and deduct the credits once per day, but that feels like a weird workaround.
From Googling it seems to be possible to do something with useCallback or React.memo, but I am very unsure how.
Give up and become a wood worker...seems like running away from the problem though.
Maybe it has something to the nested react-navigation stack and tab navigators I'm using within NavigationStructure?
Desperate things I have tried:
Wrap all sub-components of NavigationStructrue in "React.memo(..)"
Make sure I don't define a component within another component's body.
Look at loads of stack overflow posts and try to fix things, none have worked.
Code Samples
App setup with context
function App() {
const userData = useUserData();
...
return (
<>
<UserContext.Provider value={{ ...userData }}>
<NavigationStructure />
</UserContext.Provider>
</>
}
useUserData Hook with firestore snapshot listener
export const useUserData = () => {
const [user, loading] = useAuthState(authFB);
const [userAccount, setUserAccount] = useState<userAccount | null>();
const [userLoading, setUserLoading] = useState(true);
useEffect(() => {
...
unsubscribe = onSnapshot(
doc(getFirestore(), firebaseCollection.userAccount, user.uid),
(doc) => {
if (doc.exists()) {
const data = doc.data() as userAccount & firebaseRequirement;
//STACK OVERFLOW COMMENT: data CONTAINES 'credits' FIELD
...
setUserAccount(data);
}
...
}
);
}, [user, loading]);
...
return {
user,
userAccount,
userLoading: userLoading || loading,
};
};
Code Sample: Chat screen with modal
export const Chat = ({ route, navigation }: ChatScreenProps): JSX.Element => {
const ctx = useContext(UserContext);
const userAccount = ctx.userAccount as userAccount;
...
//modal visibility
const [modalVisible, setModalVisible] = useState(true);
// STACK OVERFLOW COMMENT: ISSUE IS HERE.
// FOR SOME REASON THIS STATE GET'S RE-INITALIZED (AS true) WHENEVER
// SOMETHING IN THE userAccount CHANGES.
...
return (
<>
...
<Modal
title={t(tPrefix, 'tasklistModal.title')}
visible={ModalVisible}
onClose={() => setModalVisible(false)}
footer={
...
}
>
....
</Modal>
...
</>)
}
Any change to the context does indeed rerender all consumer components whether they use the changed property or not.
But it will not unmount and mount the component which is the reason why your local state gets initialized to the default value.
So the problem is not the in the rerenders (rarely the case) but rather <Chat ... /> or one of it's parent component unmounting due to changes in the context.
It is hard to tell from the partial code examples given but I would suggest looking at how you use loading. Something like loading ? <div>loading..</div> : <Chat ... /> would cause this behaviour.
As an example here is a codesandbox which illustrates the points made.
This is a characteristic of React Context - any change in value to a context results in a re-render in all of the context's consumers. This is briefly touched on in the Caveats section in their docs, but is expanded on in third-party blogs like this one: How to destroy your app's performance with React Context.
You've already tried the author's suggestion of memoization. Memoizing your components won't prevent re-initialization, since the values in the component do change when you change your user object.
The solution is to use a third-party state management solution that relies not on Context but on its own diffing. Redux, Zustand, and other popular libraries do their own comparison so that only affected components re-render.
Context is really only recommended for values that change infrequently and would require full-app re-renders anyway, like theme changes or language selection. Try replacing it with a "real" state management solution instead.
When you go to about page from index page, RestOfTheApp rerenders. Maybe it should be this way with SSR, but nextjs added static rendering like gatsby. Isn't there a way to prevent components rerendering? Like: a header shouldn't change between pages.
about.js
function index() {
return (
<>
<RestOfTheApp>
about
</RestOfTheApp>
</>
)
}
index.js
function index() {
return (
<>
<RestOfTheApp>
index
</RestOfTheApp>
</>
)
}
You can keep component state with redux I assume, but whole page re-rendering when you just need to fetch some blog content seems bloaty. I've tested with some basic layout, it still seems lightning fast but not re-rendering whole page is the main concept of SPA's, I am a little heart broken 💔
Every component that you include in a page (under /pages) will re-render no matter what you do. But it's definitely possible to add a persistent layout which doesn't re-render in NextJs. The solution is the custom app component. You can read more about it here
Following example can be helpful to understand how you can create a persistent layout:
// /pages/_app.js
import React from 'react';
import App from 'next/app';
import Layout from '../components/Layout';
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return (
<Layout>
<Component {...pageProps}></Component>
</Layout>
)
}
}
export default MyApp
In this case, the Layout component will not re-render when you navigate between pages.
#Ankit has already given a great answer on HOW to create a persistent component. Here is WHY it works.
So what really happens when you navigate from some page A (defined in pages/a.js) to another page B (defined in pages/b.js)? First, the navigation takes place on the client-side. This means instead of fetching the rendered HTML from the server, some JavaScript is run in the browser to render the new page. (You can verify it here.) The JavaScript logic of page navigation boils down to this:
The JavaScript code of the new page component <B /> is fetched from the server, if it's not already prefetched;
Next.js will call ReactDOM.render() with 2 arguments: the first one is the new React element to render (it can be roughly thought of as the updated App component), and the second one is the DOM container element (it's always <div id="__next"></div>) that the new React element is rendered into.
In short, this process can be roughly thought of as rendering the updated App component into the <div id="__next"></div> DOM container element. React will then take care of diffing the new and old React elements and decide which part of the DOM to re-render and which part to update.
So what does the new and old React element look like? Well, the default definition of the App component looks like this:
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
// Component will be set to the current page component
return <Component {...pageProps} />
}
export default MyApp
Where the Component variable will be set to the current page component. This means the old React element will look like this:
<A {...pageProps} />
and the new React element will look like this:
<B {...pageProps} />
According to the React diffing algorithm, when comparing the new and old React element, if the two elements being compared are of different types, then the corresponding subtree will be entirely destroyed and re-rendered.
That's exactly what happens in this case. <A /> and <B /> are two different components and are considered as of different types, so the part of the DOM that corresponds to <A /> will be destroyed and re-rendered as <B />.
That's why the entire page component will be re-rendered when you navigate to a new page, even if they include common components like the header.
If you put the header in the custom App components, like this:
import Header from '../components/header'
function MyApp({ Component, pageProps }) {
return (
<div>
<Header />
<Component {...pageProps} />
</div>
)
}
export default MyApp
Then the <Header /> component will persist across page navigations, because the React diffing algorithm will consider it as the same type and will only make minimal updates to the subtree.
I'm totally new with next.js and I need your help for something I guess really basic but I cannot find my mistake or an explanation, I found nothing on the internet about it, so here I am :
Everything works when I create a file in the pages folder(I mean every file in pages folder is ok except _app.js or _document.js), I can reach the URL, but I would like to use context, layout or authentification in the future and I need to use the _app and _document override cool things but I can write anything I want in it, it seems my _app.js or _document.js are just useless, never called or I don't know but they just never work.
I tried on 2 projects, here is what I do according to the next documentation :
first, npx create-next-app to create the project, and then add an _app.js for example in pages folder and add :
import React from 'react'
import App from 'next/app'
import Nav from '../components/nav'
class MyApp extends App {
// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// static async getInitialProps(appContext) {
// // calls page's `getInitialProps` and fills `appProps.pageProps`
// const appProps = await App.getInitialProps(appContext);
//
// return { ...appProps }
// }
render() {
const { Component, pageProps } = this.props
return (
<>
<Nav />
<Component {...pageProps} />
</>
);
}
}
export default MyApp
Anybody could tell me what I am doing wrong?
Well, if anybody is going through the same issue, I found what was going on, in fact, after creating for the first time _app.js, I have to restart my docker container, or restart my app with yarn next dev if I want to see the changes or they never appear. I am going to look for more explanations on how SSR and next.js more globaly exactly work to understand their behaviour on this point. Good luck all !
I got a requirement from my client that we need to have custom themes in our react application.
Where user can select one of the available themes of his choice which will change some css attribute like font-color, font-family etc.
Right now I apply css rules to my application using className attribute.
I tried searching some of the ways of implementing the same and found one way that is having alternate css
<link rel="stylesheet" href="main.css">
<link rel="stylesheet alternate" href="light.css" id="light" title="Light">
<link rel="stylesheet alternate" href="dark.css" id="dark" title="Dark">
<script>
function enableStylesheet (node) {
node.rel = 'stylesheet';
}
function disableStylesheet (node) {
node.rel = 'alternate stylesheet';
}
</script>
And toggle rel value based on user selection.
Can any one suggest me any other way of achieving the same.
Thanks in advance.
Your usage is the correct way of implementing. But what if you've numerous theme? Loading all the css files will hamper the website. So, I would suggest you to update the source instead of loading all css files and enabling/disabling them.
node.ref = 'dark.css';
This way, you're requiring the css file only when in use. Once, the file is being used, next time it's cached. So no need to worry about them later. Obviously, it might take some time and may impact on performance if the filesize is huge, at initial use. Even though the best thing is that you don't need to wait for all.
But wait!!!
You're using react. React provides us context api and I would obviously utilize this in such scenario. Here's an excerpted example:
import {ThemeContext, themes} from './theme-context';
import ThemeTogglerButton from './theme-toggler-button';
class App extends React.Component {
constructor(props) {
super(props);
this.toggleTheme = () => {
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark,
}));
};
// State also contains the updater function so it will
// be passed down into the context provider
this.state = {
theme: themes.light,
toggleTheme: this.toggleTheme,
};
}
render() {
// The entire state is passed to the provider
return (
<ThemeContext.Provider value={this.state}>
<Content />
</ThemeContext.Provider>
);
}
}
function Content() {
return (
<div>
<ThemeTogglerButton />
</div>
);
}
ReactDOM.render(<App />, document.root);
Similar concept can be implemented using redux and with logger information to make our work easy.
I want to render SimpleModal component in handleClick , how can I achieve it through redux
can I do this way??
//ReactDOM.render(, document.getElementById("123"));
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import Redux,{createStore,combineReducers } from 'redux';
import SimpleModal from './modal.js';
import {Provider, connect} from 'react-redux';
import {displayItems} from './reducers.js';
const ecommerceAppReducer = require('./reducers.js').default;
const store = createStore(ecommerceAppReducer);
const EcommerceApp = React.createClass({
componentDidMount(){
store.dispatch({
type: 'LIST_DATA',
id: 12
});
},
handleClick: function(entity){
this.props.dispatch({
type: 'DISPLAY_INFORMATION',
entity:entity
});
**Want to render a SimpleModal here**
},
render() {
return (
<div>
<ul>{
this.props.state.displayItems.map(function(e) {
return <li><a onClick={this.handleClick.bind(this,e) }>{e.name}</a></li>
}.bind(this))
}
</ul>
</div>
);
}
});
const mapStateToProps = function (state) {
return {state};
}
const Eapp = connect(mapStateToProps)(EcommerceApp);
class App extends React.Component {
render() {
return (
<Provider store={store}>
<Eapp />
</Provider>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
In React, your render function should return what the app looks like currently. As in right now. React will take care of updating and rendering and so forth as long as you use one of the methods to inform React when it needs to rerender something.
One method is to call React.render on the root of your app. This is the worst way, but not terrible for small apps. Only recommended if you know what you're doing and even then there are probably better methods.
The next is to use setState() in your component. React will call that particular component's render method sometime after that. It's much more precise in that not your entire app gets rerendered (although you can always stop the rendering cascade by implementing shouldComponentUpdate judiciously).
Next is to call forceUpdate which is terrible to use unless you are really sure of what it is you're getting yourself into. React-Redux uses this because they do know what they're getting into.
And finally, there's React-Redux, which isn't really another way for React to render your component. But it is a new way for the developer. This is by far the recommended way to do things.
To use it, you just follow the connect prescribed method for transforming your Redux state into props for your component.
This requires reading the a Redux docs. It's a long and arduous process that is guaranteed to make anyone a better developer.
In your mapStateToProps implementation it's important to be very selective with what parts of the state you pass along to your component.
Don't just go and pass the entire Redux state. This would cause your entire app to rerender if anything at all changed anywhere in your app. Less than optimal. Only pass what you need. Don't even pass what child components need. They get their own connect.
Now onwards and forwards we go.
You want handleClick to pop up some stuffs and show it to the user.
Method 1: Use alert. It's ugly and super simple. It provides a terrible user experience so it's not recommended.
Method 2: Use React-Redux. dispatch an action that causes your reducer to put some data in the state that lets your app know to show the data. Looks like you are already doing that!
Redux will then inform React-Redux that something has changed.
React-Redux will then check if any of your components use the information in the state that was just changed. It knows what you use because this is what you returned from your mapStateToProps function.
React-Redux will then tell React to rerender any of the components that it finds need updating.
When your component's render method gets called, you'll get the new info in the props. So do:
render() {
return (
<div>
{Boolean(this.props.modalOpen) && <MyConnectedModal />}
<ul>{
this.props.displayItems.map(function(e) {
return <li key={e.name}><a onClick={this.handleClick.bind(this, e) }>{e.name}</a></li>
}.bind(this))
}
</ul>
</div>
);
}
There's still plenty wrong with the above code. You should, for instance, never bind in render.
Note that the modal is a component apart. It gets its data from React-Redux and not from props passed by the parent. This means your EcommerceApp component does not have to be responsible for updating the modal if any data it's displaying changes. Redux will take care of that. Actually with React-Redux's help of course. And React, naturally. Not necessarily in that order.
To recap what's going on here: Your render method tells React not what to pop up, but what the final result should look like. This is an enormous difference and pretty much the entire point of React.
You never tell React what changed. You always tell it what the final result should look like. React will then go and figure out what happened and will find an efficient way to show it in your browser window or electron or nw.js desktop app or native mobile app or anywhere else React worx.