On my React page, changing the language only works after browser refresh. Have tried all possible suggestions from previous posts and nothing. It does work as expected only for strings on the App.js component. Any help appreciated.
here is my i18n.js file
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
const resources = {
'en': {translation: require('./translations/en.json')},
'th': {translation: require('./translations/th.json')},
'pt': {translation: require('./translations/pt.json')},
}
i18n
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
debug: true,
fallbackLng: 'en',
// lng: 'th',
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
resources
});
export default i18n;
My change language function is this:
handleLanguageChange = (item) => {
i18n.changeLanguage(item.key, () => console.log('lanh1', i18next.language))
// this.forceUpdate()
}
Importing on App.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import rootReducer from './store/reducers/rootReducer';
import thunk from 'redux-thunk';
import { applyMiddleware, createStore } from 'redux';
import { Provider } from 'react-redux';
import './i18n';
const store = createStore(rootReducer, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>,
document.getElementById('root')
);
reportWebVitals();
and here is how i render translations:
import React, { Component } from 'react';
import { Navigate} from "react-router-dom";
import { Button, Container, Grid } from '#mui/material';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { setCurRoute } from '../../store/actions/authAction';
import Background from '../../img/header-img.jpg';
import i18next from 'i18next';
// import i18n from '../../i18n';
class LandingPage extends Component {
render() {
return (
<div
style={{
backgroundImage: `url(${Background})`,
backgroundPosition: 'center',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat'
}}
>
<h1 style={{textAlign: 'center'}}>{i18next.t('headline_one_one')}<br />{i18next.t('headline_one_two')}</h1>
<h4 style={{textAlign: 'center', lineHeight: 2, border: '2'}}>
{i18next.t('headline_two')}
</h4>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(LandingPage)
In react, try to use the useTranslation hook or the withTranslation HOC. That will detect the language change.
Try this if it's a class component:
componentDidUpdate(prevProps, prevState) {
if (this.props.t !== prevProps.t) {
console.log(this.props.i18n.language);
}
}
As NextJs pre-rendering is Static Generation or Server-side Rendering of the html of the pages, we cannot use i18n.changeLanguage like in a "normal" React app and we have to use the next router like this :
import {useRouter} from "next/router";
const router = useRouter();
function changeLang(locale:string):void {
router.push({
route: router.route,
query: router.query
}, router.asPath, { locale });
}
changeLang("en");
Related
I'm trying to render a material-ui component inside renderToStaticMarkup (because I have to integrate with another library) but none of the css styles are applied:
import * as React from "react";
import ReactDOM from "react-dom/client";
import Button from "#mui/material/Button";
import { styled } from "#mui/material";
import { renderToStaticMarkup } from "react-dom/server";
const StyledButton = styled(Button)(() => ({
backgroundColor: "red"
}));
ReactDOM.createRoot(document.querySelector("#root")).render(
<React.StrictMode>
<div
dangerouslySetInnerHTML={{
__html: renderToStaticMarkup(<StyledButton>Test</StyledButton>)
}}
/>
</React.StrictMode>
);
https://codesandbox.io/s/heuristic-bouman-d1mogi?file=/index.js:0-527
how are you doing? I badly cannot connect GA with React, im very stucked and all the videos that i saw the ID connector its start with UA, please help me
import './App.css';
// import Header from "../Header/header"
import Header2 from "../Header2/header"
import Footer from "../Footer/footer"
import Switch from "../Switch/switch"
import {BrowserRouter as Router} from "react-router-dom";
import React, {useEffect} from "react"
import ReactGa from "react-ga";
/**** Icons ****/
import { library } from '#fortawesome/fontawesome-svg-core'
import { fab, faFacebookSquare, faGoogle, faInstagramSquare, faWhatsappSquare} from '#fortawesome/free-brands-svg-icons'
import { fas, faBars, faIdCard, faGlobeAmericas, faCalendarAlt, faArrowUp} from '#fortawesome/free-solid-svg-icons'
library.add(fas, fab, faBars, faFacebookSquare, faInstagramSquare, faWhatsappSquare, faGoogle, faIdCard, faGlobeAmericas, faCalendarAlt, faArrowUp)
function App() {
useEffect(() => {
ReactGa.initialize('G-YZ9S63BMYY')
ReactGa.pageview(window.location.pathname)
}, [])
useEffect(() => {
console.log("hola", window.location.pathname)
})
return (
<Router>
<Header2 />
<React.StrictMode>
<Switch />
</React.StrictMode>
<Footer />
</Router>
);
}
export default App;
From now on thanks for all folks :)
You have to use React for GA4: https://www.npmjs.com/package/react-ga4
I am setting up the react-i18n-next hook to translate my app and i followed the example that the react-i18n-next use but it throws error like below:
i18next::translator: missingKey
en-US
translation
App.js
import React, { Component, Suspense } from "react";
import { useTranslation, withTranslation, Trans } from "react-i18next";
// use hoc for class based components
class LegacyWelcomeClass extends Component {
render() {
const { t } = this.props;
return <h2>{t("title")}</h2>;
}
}
const Welcome = withTranslation()(LegacyWelcomeClass);
// Component using the Trans component
function MyComponent() {
return <Trans i18nKey="description.part1" />;
}
// page uses the hook
function Page() {
const { t, i18n } = useTranslation();
const changeLanguage = lng => {
i18n.changeLanguage(lng);
};
return (
<div className="App">
<div className="App-header">
<Welcome />
<button type="button" onClick={() => changeLanguage("de")}>
de
</button>
<button type="button" onClick={() => changeLanguage("en")}>
en
</button>
</div>
<div className="App-intro">
<MyComponent />
</div>
<div>{t("description.part2")}</div>
</div>
);
}
// loading component for suspense fallback
const Loader = () => (
<div className="App">
<div>loading...</div>
</div>
);
// here app catches the suspense from page in case translations are not yet loaded
export default function App() {
return (
<Suspense fallback={<Loader />}>
<Page />
</Suspense>
);
}
i18n.js
import i18n from "i18next";
import Backend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: "en",
debug: true,
interpolation: {
escapeValue: false // not needed for react as it escapes by default
}
});
export default i18n;
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
// import i18n (needs to be bundled ;))
import "./i18n";
ReactDOM.render(<App />, document.getElementById("root"));
sample code available here and I don't know what I am missing, It would be better to get some basic working example,s and any help on this really helpful.
My requirement is, I need to translate my app to some other language like from en to fr, the only context I have is en file.
There are certain things you need to do in the above code
First of all you need to make two translation files, in which you are missing some keys and their values.
let suppose translationEN.json -
{
"title": "Title",
"Welcome to React": "Welcome to React and react-i18next",
"description": {
"part2": "some description"
}
}
and translationDE.json -
{
"title": "DE ***** Title",
"Welcome to React": "DE **** Welcome to React and react-i18next",
"description": {
"part2": "DE **** some description"
}
}
Import the above files in i18n.js and Add resources and lng in i18n init
import translationEN from "../src/translationEN.json";
import translationDE from "../src/translationDE.json";
const resources = {
en: {
translation: translationEN
},
de: {
translation: translationDE
}
};
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources,
lng: "en",
Solution is added here
i need help
i got this error
./src/components/Header/Header.js
Attempted import error: 'UseTranslation' is not exported from 'react-i18next'.
its a new projects where i have install the https://react.i18next.com step by step
but i got problem with the import UseTranslation
in header.js i got just this
import { useTranslation } from 'react-i18next';
//style
import "./Header.scss";
class Header extends Component {
render() {
const { t, i18n } = useTranslation();
return (
<div className="container-header">
<div className="container-header__main">
<div className="container-header__main-overlay">
<div className="container-header__main-overlay__text">
<div className="container-header__main-overlay__text__title">
{t('hello')}
</div>
<div className="container-header__main-overlay__text__subtitle">
{t('hello2')}
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Header;
this is my i18n.js this is ok i think
import i18n from "i18next";
import { reactI18nextModule } from "react-i18next";
import EN from './assets/translation/en.json';
import CZ from './assets/translation/cz.json';
const resources = {
en: {
translation: EN
},
cz:{
translation: CZ
}
};
i18n
.use(reactI18nextModule)
.init({
resources,
lng: "en",
fallbackLng: "en",
useSuspense: false,
});
export default i18n;
the useTranslation it use for hook but you use classComponent you shold use Hoc
import { withTranslation } from 'react-i18next';
const {t,i18n} =this.props
{t('hello2')}
export default withTranslation()(Header);
and in your index.js add Suspense
import React, { Component, Suspense } from 'react';
<Suspense fallback={<div>Loading....</div>}>
<App />//your Component
</Suspense>
Trying to use an outlined button from material UI : https://github.com/mui-org/material-ui/blob/master/docs/src/pages/demos/buttons/OutlinedButtons.js
But get the error - "Unexpected use of 'self' no-restricted-globals"
And I don't have permissions to change it in the lodash.throttle/index.js file.
Is there any workaround for this that anyone knows of?? (It's literally just the sample code btw)
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '../node_modules/#material-ui/core/styles';
import Button from '../node_modules/#material-ui/core/Button';
const styles = theme => ({
button: {
margin: theme.spacing.unit,
},
input: {
display: 'none',
},
});
function OutlinedButtons(props) {
const {classes} = props;
return (
<div>
<Button variant="outlined" className={classes.button}>
Default
</Button>
</div>
);
}
OutlinedButtons.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(OutlinedButtons);
After a request. App.js:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import PropTypes from 'prop-types';
import { withStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import UserGroup from './components/user_group';
import ButtonTest from './components/Button';
import OutlinedButtons from './components/floatingButton'
class App extends Component {
render() {
return (
<MuiThemeProvider>
<div className="App">
<header className="App-header">
{ OutlinedButtons }
</header>
</div>
</MuiThemeProvider>
);
}
}
export default App;
And index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();