Why isn't my t() texts refreshing in localhost/en but refreshing in localhost/fr on i18n.changeLanguage()? - next.js

Hi
I just made a website with a darkmode and multilanguage support to test around but I ran into an issue.
the code
I got rid of all things that aren't an issue
portfolio/src/pages/index.tsx
import { useTranslation } from 'react-i18next'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
export default () => {
const { t,i18n } = useTranslation('common')
return <div onClick={()=>i18n.changeLanguage(i18n.language=='fr'?'en':'fr')}>
<div>{i18n.language}</div>
<span>{t('debug')}</span>
</div>
}
export async function getStaticProps({ locale }:any) {
return {
props: {
...(await serverSideTranslations(locale, ['common'])),
// Will be passed to the page component as props
},
};
}
portfolio/src/public/locales/en/common.js
{"debug":"english"}
portfolio/src/public/locales/fr/common.js
{"debug":"français"}
portfolio/next-i18next.config.js
const path = require("path");
module.exports = {
debug: false,
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr'],
},
localePath: path.resolve('./src/public/locales'),
};
portfolio/src/pages/_app.tsx
import '../styles/globals.css'
import type { AppProps } from 'next/app'
import {appWithTranslation} from 'next-i18next'
export default appWithTranslation(({ Component, pageProps }: AppProps) => {
return <Component {...pageProps} />
})
The issue
When I do npm run dev and go to http://localhost:3000/fr, the page defaults to french and works good I can swap between languages without problems but when i go to http://localhost:3000/en the t('debug') doesn't translate when the i18n.language changes as intended.

Found what I wanted
So basicaly I need to use a next Link that will change the local and the link
Code application
index.js
//...
export default () => {
const { t,i18n } = useTranslation('common')
return (
<div>
<Link
href={i18n.language=='fr'?'/en':'/fr'}
locale={i18n.language=='fr'?'en':'fr'}
>{i18n.language}</Link>
<div>{t('debug')}</div>
</div>
)
}
//...
result
Now the text changes as intended both in the /fr and /en because it switches between the 2 however the result is far from smooth. It reloads the page and i'd like to avoid that because I use some animations on it.
Found what i wanted part 2
Browsing through the next-i18next documentation I found what I wanted.
solution
I needed to load the props using getStaticProps and in the serverSideTranslation function i needed to pass as argument the array off ALL the language necessary to load the page ['en','fr'] because i switched between the 2

Related

How to use SSR with Stencil in a Nuxt 3 Vite project?

In Nuxt 2 I could use server-side rendered Stencil components by leveraging the renderToString() method provided in the Stencil package in combination with a Nuxt hook, like this:
import { renderToString } from '[my-components]/dist-hydrate'
export default function () {
this.nuxt.hook('generate:page', async (page) => {
const render = await renderToString(page.html, {
prettyHtml: false
})
page.html = render.html
})
}
Since the recent release of Stencil 2.16.0 I'm able to use native web components in Nuxt 3 that is powered by Vite. However I haven't found a way to hook into the template hydration process. Unfortunately there is no documentation for the composable useHydration() yet.
Does anybody know how I could get this to work in Nuxt 3?
I had the same problem. I solved it via a module.
Make a new custom nuxt module. documentation for creating a module
In the setup method hook into the generate:page hook:
nuxt.hook('generate:page', async (page) => {
const render = await renderToString(page.html, {
prettyHtml: true,
});
page.html = render.html;
});
documentation for nuxt hooks
documentation for stencil hydration (renderToString)
Register the css classes you need via nuxt.options.css.push(PATH_TO_CSS)
Register the module in the nuxt config.
Note: Make sure in the nuxt.config.ts the defineNuxtConfig gets exported as default.
Tap the vue compiler options in the nuxt config:
vue: {
compilerOptions: {
isCustomElement: (tag) => TEST_TAG_HERE,
},
},
This depends on how you wan't to use the custom elements. In my case I defined the elements over the stencil loader in my app.vue file:
import { defineCustomElements } from '<package>/<path_to_loader>';
defineCustomElements();
You could also import the elements you need in your component and then define them right there, for example in a example.vue component:
import { CustomElement } from '<package>/custom-elements';
customElements.define('custom-element', CustomElement);
Here is an example from my module and config:
./modules/sdx.ts
import { defineNuxtModule } from '#nuxt/kit';
import { renderToString } from '#swisscom/sdx/hydrate';
export default defineNuxtModule({
meta: {
name: '#nuxt/sdx',
configKey: 'sdx',
},
setup(options, nuxt) {
nuxt.hook('generate:page', async (page) => {
const render = await renderToString(page.html, {
prettyHtml: true,
});
page.html = render.html;
});
nuxt.options.css.push('#swisscom/sdx/dist/css/webcomponents.css');
nuxt.options.css.push('#swisscom/sdx/dist/css/sdx.css');
},
});
Important: This only works if the stenciljs package supports hydration or in other words has a hydrate output. Read more here
./nuxt.config.ts
import { defineNuxtConfig } from 'nuxt';
//v3.nuxtjs.org/api/configuration/nuxt.config export default
export default defineNuxtConfig({
typescript: { shim: false },
vue: {
compilerOptions: {
isCustomElement: (tag) => /sdx-.+/.test(tag),
},
},
modules: ['./modules/sdx'],
});
./app.vue
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>
<script setup lang="ts">
import { defineCustomElements } from '#swisscom/sdx/dist/js/webcomponents/loader';
defineCustomElements();
// https://v3.nuxtjs.org/guide/features/head-management/
useHead({
title: 'demo',
viewport: 'width=device-width, initial-scale=1, maximum-scale=1',
charset: 'utf-8',
meta: [{ name: 'description', content: 'demo for using a stencil package in a nuxt ssr app' }],
bodyAttrs: {
class: 'sdx',
},
});
</script>
Update
I tested my setup with multiple components and it looks like you cannot define your components in the module. I updated the answer to my working solution.
I've found defining a plugin using the 'render:response' hook to work for me:
server/plugins/ssr-components.plugin.ts
import { renderToString } from '#my-lib/components/hydrate';
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('render:response', async (response) => {
response.body = (await renderToString(response.body)).html;
});
});
Perhaps it will work for you :)
Try this in defineNuxtPlugin
nuxtApp.hook('app:rendered', () => {
const response = nuxtApp.ssrContext?.res
if (!response)
return
const end = response.end
response.end = function(chunk) {
chunk = 'hijacked'
end(chunk)
}
})

NEXT JS: Build exportPathMap for a dynamic page Route

I wanted to build a static export for my NEXT project that looks like following:
- pages
---- index.tsx
---- [pageRoute].tsx
Now I want to statically generate routeId for home page that I have handled as shown below:
import { useRouter } from 'next/router';
import React from 'react';
import { PAGE_ROUTES } from '../constants/config';
import Home from './Home/Home';
type Props = {};
export default function Base({}: Props) {
const router = useRouter();
const route = router.query.pageRoute as string;
let RenderComponent = <div>404: Page Not Found</div>;
switch (route) {
case PAGE_ROUTES.HOME: {
RenderComponent = <Home />;
break;
}
default: {
}
}
return (
<div className='flex flex-col items-center max-w-sm mx-auto'>
{RenderComponent}
</div>
);
}
I am not sure what do I specify in exportPathMaps in next.config.js in order to create static export of home page:
/** #type {import('next').NextConfig} */
module.exports = {
reactStrictMode: true,
exportPathMap: async function (
defaultPathMap,
{ dev, dir, outDir, distDir, buildId }
) {
return {
'/': { page: '/' },
// how do I add configuration for '/home': {page: '/[pageRoute]',query:{pageRoute:'home'}}
};
},
};
when I do this:
'/home': { page: '/[pageRoute]', query: { pageRoute: 'home' } },
It throws error saying:
Error: you provided query values for /home which is an auto-exported page. These can not be applied since the page can no longer be re-rendered on the server. To disable auto-export for this page addgetInitia
lProps
In order to statically pre-render dynamic paths, you should return them from getStaticPaths:
import { useRouter } from 'next/router';
import React from 'react';
import { PAGE_ROUTES } from '../constants/config';
import Home from './Home/Home';
import type { GetStaticPaths } from 'next'
export const getStaticPaths: GetStaticPaths = async () => {
const paths = Object.values(PAGE_ROUTES)
.map(route => [{ params: { pageRoute: route } }])
return {
paths,
fallback: false, // meaning any path not returned by `getStaticPaths` will result in a 404 page
}
}
type Props = {};
export default function Base({}: Props) {
return (
<div className='flex flex-col items-center max-w-sm mx-auto'>
<Home />
</div>
);
}
And, as #juliomalves said, in that case you don't need exportPathMap in next.config.js.
For custom 404 page create 404.tsx in /pages
More about getStaticPaths - https://nextjs.org/docs/api-reference/data-fetching/get-static-paths
fallback: false - https://nextjs.org/docs/api-reference/data-fetching/get-static-paths#fallback-false

next-i18next is not working with serversideprops in dynamic pages after deploying on vercel

I'm using next-i18next module for multilingual support.
I have some static pages and dynamic pages as well. both working fine on local.
I deployed all static pages on vercel, all worked fine on vercel. But dynamic page is not working on vercel. it shows 404 page for that dynamic page.
Below is the code of the dynamic page. (pages/test-page/[questionId].js)
import { useState, useEffect } from "react";
import {Layout} from "#components/common";
import { useRouter } from 'next/router';
import { useTranslation } from 'next-i18next'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import { TestComponent } from '#components/TestComponent'
const TestPage = () =>
{
const { t } = useTranslation('common')
const router = useRouter()
const {questionId} = router.query;
const [isApiLoaded,setIsApiLoaded] = useState(false)
return (
<TestComponent
t={t}
isApiLoaded={isApiLoaded}
setIsApiLoaded={setIsApiLoaded}
/>
)
}
TestPage.Layout = Layout
export const getServerSideProps = async ({ locale }) => ({
props: {
...(await serverSideTranslations(locale, ['home', 'common']))
}
});
export default TestPage;
How to fix this issue?
Adding localePath in next-i18next.config.js did help in my case.
const path = require('path')
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'de'],
localePath: path.resolve('./public/locales')
}
};
I was facing the same issue and for a temporary fix I used the i18n object from next-i18next that has a function called getResource that gets the current locale with its translations
// import { i18n } from 'next-i18next';
// import { useRouter } from 'next/router';
const [translation, setTranslation] = useState({});
useEffect(() => {
const bundle = i18n.getResource(locale, 'common');
setTranslation(bundle);
}, []);
And to avoid rewrite the code with the t function, you could use
// LINK https://stackoverflow.com/a/43849204/14263138
const t = (word) => word
.split('.')
.reduce((p, c) => (p && p[c]) || null, translation);
With this applied, you don't need to use the getServerSideProps
Although the post is now old, I share the solution that solved the problem in my project (focus on the addition of localePath):
const path = require('path');
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'it', 'de', 'es', 'fr', 'ja']
},
defaultNs: 'shared',
fallbackLng: { default: ['en', 'it', 'de', 'es', 'fr', 'ja'] },
localePath: path.resolve('./public/locales'),
};
I specify that localePath should not be included among the properties of i18n as indicated in another answer as doing so produces a type error.
Also make sure to use getServerSideProps and not getStaticProps on pages, for example:
export async function getServerSideProps({ locale }) {
return {
props: {
...(await ssrTranslations(locale, ['login', 'shared'])),
},
};
}
Import the serverSideTranslations
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
Now from the getServerSideProps, pass the ..(await serverSideTranslations(locale, ["common"])), with the props.
export const getServerSideProps: GetStaticProps = async ({
locale,
locales,
query
}: any) => {
return {
props: {
...(await serverSideTranslations(locale, ["common"])),
}
}
};
Now add your language strings inside
/public/locales/en/common.json
For example
{
"home": {
"Test": "Test"
}
}
You can add more language strings inside the locales directory.
Restart your Next.js app. It will work.

Next.js and Styled Components go out of sync between the server and the client on refresh

I have a Next.js app using styled components. On first load of any page, there are no complaints, and everything looks properly styled. When I refresh a page however, everything still looks proper, but I get a console error reading:
Warning: Prop `className` did not match. Server: "sc-TXQaF bfnBGK" Client: "sc-bdnylx kKokSB"
I've tried simplifying the styles on the specific component, and the error persists. I've tried removing the component entirely from the DOM, and that results in the same error on the next element in the DOM. So it seems to be a global issue.
I've followed the guide for using Next.js and Styled Components found here: https://github.com/vercel/next.js/tree/master/examples/with-styled-components
I have the .babelrc file in the root:
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}
I have the _document.js file in my pages directory:
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
Here is an example of one of my styled components:
import styled from 'styled-components';
export const Block = styled.div`
margin: ${props => props.small ? '2rem 0' : '4rem 0'};
margin-top: ${props => props.clearTop ? '0' : null};
`;
... although I've tried to dumb it down to something as simple as this with no change in the console error:
import styled from 'styled-components';
export const Block = styled.div`
position: relative;
`;
Finally, here's a dumbed down page that still produces the error:
import { useContext, useEffect } from 'react';
import { useRouter } from 'next/router';
import Layout from '../components/layout';
import { Block } from '../components/styled/Block';
import { userContext } from '../context/userContext';;
function Profile() {
const router = useRouter();
const { loggedIn } = useContext(userContext);
useEffect(() => {
if (!loggedIn) router.push('/login');
}, [loggedIn]);
return (
<Layout>
<Block>
<h1>Test</h1>
</Block>
</Layout>
)
}
export default Profile;
Kind of at my wits end here.
I believe I figured out an answer. I didn't have the dev dependency for babel styled components.
npm install babel-plugin-styled-components --save-dev
Your package.json file should have this:
"devDependencies": {
"babel-plugin-styled-components": "^1.11.1"
}
After this was installed, along with the _document.js and .babelrc files correctly placed in your app, you shouldn't have any problems.
I had this issue for the last 1 month and finally got a solution that worked for me!
So the solution here is to get the styling exclusively from the server.
from the docs:
Basically you need to add a custom pages/_document.js (if you don't
have one). Then copy the logic for styled-components to inject the
server side rendered styles into the <head>
To solve this issue is you need something like this in your Document component:
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
The final step (if the error persists) is to delete the cache: delete the .next folder and restart the server
The full example code from Next documentation is Here
with the Next Complier on the latest version of next, you should only update your next.config file and _document file, and you will be all set. Babel will cause conflict with the NextJS compiler.
Here you can check the files. If you don't use TS, just replace
ctx: DocumentContext
with only
ctx
Example app with styled-components

TypeError: Object(...) is not a function (redux)

I am having a TypeError (TypeError: Object(...) is not a function) when I want to dispatch an action. I'm not using any middleware and don't know what I can do to solve it. I had this error already yesterday but somehow managed to solve it (i donk know how i did this)
This is the App.js:
import React from "react";
import { store } from "../store";
import { withdrawMoney} from "../actions";
const App = () => {
return (
<div className="app">
<div className="card">
<div className="card-header">
Welcome to your bank account
</div>
<div className="card-body">
<h1>Hello, {store.getState().name}!</h1>
<ul className="list-group">
<li className="list-group-item">
<h4>Your total amount:</h4>
{store.getState().balance}
</li>
</ul>
<button className="btn btn-primary card-link" data-amount="5000" onClick={dispatchBtnAction}>Withdraw $5,000</button>
<button className="btn btn-primary card-link" data-amount="10000" onClick={dispatchBtnAction}>Witdhraw $10,000</button>
</div>
</div>
</div>
);
}
function dispatchBtnAction(e) {
store.dispatch(withdrawMoney(e.target.dataset.amount));
}
export default App;
Here is the actioncreator:
function withdrawMoney(amount) {
return {
type: "ADD_TODO",
amount
}
}
If you need here is the reducer:
export default (state, action) => {
console.log(action);
return state
}
As you can see I'm a very new to redux but I'd like to know what mistake I make all the time when dispatching an action. Thanks
I believe the issue is that you aren't exporting the withdrawMoney function, so you aren't able to call it in the component that you're attempting to import into.
try:
export function withdrawMoney(amount) {
return {
type: "ADD_TODO",
amount
}
}
Another subtle mistake that will cause this error is what I tried to do, don't accidentally do this:
import React, { useSelector, useState ... } from 'react'
it should be:
import React, { useState } from 'react'
import { useSelector } from 'react-redux'
Try to install :
npm i react#next react-dom#next and run again
const mapStateToProps = state => ({
Bank: state.Bank,
});
function mapDispatchToProps(dispatch) {
return {
dispatch,
...bindActionCreators({ getBanks, addBank }, dispatch)
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(BankComponent);
this worked like a Charm for me .
bit Late to party,
to me it was about casing.
export const addTodo = text => ({
type: ADD_TODO,
desc: text
});
export const removeTodo = id=> ({
type: REMOVE_TODO,
id: id
})
export const increaseCount = () => ({
type: INCREASE_COUNT
});
export const decreaseCount = () => ({
type: DECREASE_COUNT
})
when I renamed all those like
export const AddTodo = text => ({
type: ADD_TODO,
desc: text
});
export const RemoveTodo = id => ({
type: REMOVE_TODO,
id: id
})
export const IncreaseCount = () => ({
type: INCREASE_COUNT
});
export const DecreaseCount = () => ({
type: DECREASE_COUNT
})
it worked.
I spent hours debugging this, turns out I was doing this:
import React, { connect } from "react";
Instead of
import React from "react";
import { connect } from "react-redux";
It's weird the former didn't throw an error, but it will cause the problem!
First problem I see right off the bat is your reducer is not setup to do anything with the dispatched withdrawMoney action creator.
export default (state, action) => {
switch (action.type) {
case "ADD_TODO": {
return {
...state,
amount: action.amount,
};
}
default:
return state;
}
};
If this does not help, the code from your other files would be helpful.
It may not be the main issue, but it looks like you're not using the React-Redux library to work with the store. You can reference the store directly in your React components, but it's a bad practice. See my explanation for why you should be using React-Redux instead of writing "manual" store handling logic.
After updating react-redux to version 7.2.0+ I was receiving this error anytime I wrote:
const dispatch = useDispatch()
I stopped my application and re-ran it with npm start, and everything is working now.
I was using redux toolkit and for me the problem was an extra '}'
such that my 'reducers' object, in 'createSlice' function, already had a closing curly brace before my second reducer
and my 2nd reducer was actually outside the 'reducers' object,
making it not a reducer and hence not working even when you export or import it properly.
So the problem is not in your export or import, but actually where your function is defined.
This may be different for other users, but in my case this turned out to be the cause of this error.

Resources