Tailwindcss does not get loaded in react application - javascript

I am using the following packages and have installed tailwindcss in the following project folder /home/admin/Desktop/Code/main_project/client/package.json:
{
"name": "react-app",
"version": "1.0",
"private": true,
"dependencies": {
"babel-eslint": "10.0.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.4",
"react-router": "^6.3.0",
"react-scripts": "3.2.0",
"redux": "^4.1.1",
"redux-thunk": "^2.3.0",
"web-vitals": "^1.0.1",
"web3": "^1.6.1",
"web3-eth-contract": "^1.5.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"autoprefixer": "^10.4.7",
"postcss": "^8.4.14",
"tailwindcss": "^3.0.24"
}
}
My tailwind.config.js looks like the following:
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
As you can see my react-project lies in a subfolder.
My postcss.config.js looks like the following:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
This is my index.css:
#tailwind base;
#tailwind components;
#tailwind utilities;
In my index.js I am loading my index.css:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import store from "./redux/store";
import { Provider } from "react-redux";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
My App.js looks like the following:
import React, { useEffect, useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { connect } from "./redux/blockchain/blockchainActions";
import { fetchData } from "./redux/data/dataActions";
import "./App.css";
function App() {
const dispatch = useDispatch();
const blockchain = useSelector((state) => state.blockchain);
const data = useSelector((state) => state.data);
const [CONFIG, SET_CONFIG] = useState({
CONTRACT_ADDRESS: "",
SCAN_LINK: "",
NETWORK: {
NAME: "",
SYMBOL: "",
ID: 0,
},
NFT_NAME: "",
SYMBOL: "",
MAX_SUPPLY: 1,
WEI_COST: 0,
DISPLAY_COST: 0,
GAS_LIMIT: 0,
MARKETPLACE: "",
MARKETPLACE_LINK: "",
SHOW_BACKGROUND: false,
});
const getData = () => {
if (blockchain.account !== "" && blockchain.smartContract !== null) {
dispatch(fetchData(blockchain.account));
}
};
const getConfig = async () => {
const configResponse = await fetch("/config/config.json", {
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
const config = await configResponse.json();
SET_CONFIG(config);
};
useEffect(() => {
getConfig();
}, []);
useEffect(() => {
getData();
}, [blockchain.account]);
return (
<>
<h1 className="text-3xl font-bold underline">Welcome</h1>
<>
);
}
export default App;
However, the components in my App.js do not get rendered with tailwindcss.
Any suggestions what I am doing wrong?
I appreciate your replies!

Related

MUI 5 Cannot read properties of undefined (reading 'up'), When using makestyles

I have recently build a react app with MUI-5 and it was working fine but now i am facing a weird issue where my app won't start and i see bunch of mui errors. These errors occurred after i deleted the yarn.lock file and freshly added all packages. I have tried every solution but its not working.
Error:
MUI: The styles argument provided is invalid.
You are providing a function without a theme in the context.
Uncaught TypeError: Cannot read properties of undefined (reading 'up')
package.json file:
{
"name": "doctor",
"version": "0.1.0",
"private": true,
"dependencies": {
"#date-io/date-fns": "^2.11.0",
"#date-io/moment": "^2.11.0",
"#emotion/react": "^11.7.1",
"#emotion/styled": "^11.6.0",
"#material-ui/core": "^4.12.4",
"#mui/icons-material": "^5.2.5",
"#mui/lab": "^5.0.0-alpha.62",
"#mui/material": "^5.10.7",
"#mui/styles": "^5.10.7",
"#mui/system": "^5.10.6",
"#reduxjs/toolkit": "^1.7.1",
"#stripe/react-stripe-js": "^1.7.0",
"#stripe/stripe-js": "^1.22.0",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^12.0.0",
"#testing-library/user-event": "^13.2.1",
"#types/react-qr-reader": "^2.1.4",
"autoprefixer": "^10.4.0",
"web-vitals": "^2.1.0",
"yup": "^0.32.11"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#types/chart.js": "^2.9.35",
"#types/file-saver": "^2.0.5",
"#types/jest": "^27.0.1",
"#types/node": "^16.7.13",
"#types/react": "^17.0.20",
"#types/react-dom": "^17.0.9",
"#types/react-redux": "^7.1.21",
"#types/react-router-dom": "^5.1.7",
"#types/react-table": "^7.7.9",
"#types/redux-logger": "^3.0.9",
"chartjs-plugin-datalabels": "^2.0.0",
"lodash": "^4.17.21"
},
"resolutions": {
"#types/react": "17.0.2",
"#types/react-dom": "17.0.2"
}
}
app.tsx file;
import React from "react";
import { ThemeProvider } from "#material-ui/core/styles";
import "./App.css";
import { loadStripe } from "#stripe/stripe-js";
import { Elements } from "#stripe/react-stripe-js";
// redux
import { Provider } from "react-redux";
import store, { persistor } from "./redux/store";
import { PersistGate } from "redux-persist/integration/react";
// Routes
import { ConnectedRouter } from "connected-react-router";
import history from "./redux/history";
import Router from "./Router";
// Theme
import { SnackbarProvider } from "notistack";
import CustomSnackbarProvider from "./providers/CustomSnackbarProvider";
import muiTheme from "./constants/theme";
import { makeStyles } from "#mui/styles";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler,
BarElement,
} from "chart.js";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { useLocation } from "react-router-dom";
import AccessControlWrapper from "./components/AccessControlWrapper";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
BarElement,
ChartDataLabels,
Filler
);
declare var process: {
env: {
REACT_APP_STRIPE_PUBLISH_KEY: string;
REACT_APP_STRIPE_CLIENT_SECRET: string;
};
};
const stripePromise = loadStripe(process.env.REACT_APP_STRIPE_PUBLISH_KEY);
function App() {
return (
<Provider store={store}>
<PersistGate persistor={persistor} loading={null}>
<Elements stripe={stripePromise}>
<ConnectedRouter history={history}>
<ThemeProvider theme={muiTheme}>
<SnackbarProvider
maxSnack={3}
anchorOrigin={{
vertical: "top",
horizontal: "center",
}}
>
<CustomSnackbarProvider>
<AccessControlWrapper>
<Router />
</AccessControlWrapper>
</CustomSnackbarProvider>
</SnackbarProvider>
</ThemeProvider>
</ConnectedRouter>
</Elements>
</PersistGate>
</Provider>
);
}
export default App;
theme config file:
import { createTheme } from "#material-ui/core/styles";
declare module "#mui/material/styles" {
interface BreakpointOverrides {
xs: true; // removes the `xs` breakpoint
sm: true;
md: true;
lg: true;
xl: true;
xxl: true;
}
}
const theme = {
palette: {
background: {
default: "#FBFBFB",
},
primary: {
light: "#9D9DA5",
main: "#2EC2A5",
contrastText: "#fff",
},
secondary: {
light: "#ff7961",
main: "#24344B",
dark: "#ba000d",
contrastText: "#000",
},
},
};
const BREAKPOINTS = {
xs: 0,
sm: 600,
md: 900,
lg: 1200,
xl: 1536,
xxl: 1800,
};
let muiTheme = createTheme({
breakpoints: {
values: BREAKPOINTS,
},
...theme,
});
export default muiTheme;
Styles.tsx
import { Theme } from "#mui/system";
import { makeStyles } from "#mui/styles";
export const useStyles = makeStyles((theme: Theme) => ({
intro: {
padding: "0 2rem",
[theme.breakpoints.up("lg")]: {
padding: "0 4rem !important",
},
},
}));
I've been stuck with this problem for couple of days. I don't know what i am doing wrong. i have already wrapped my routes with ThemeProvider but still its throwing these errors.
According to the docs:
Using the theme context
Starting from v5, MUI no longer uses JSS as its default styling solution. If you still want to use the utilities exported by #mui/styles and they depend on the theme, you will need to provide the theme as part of the context. For this, you can use the ThemeProvider component available in #mui/styles, or, if you are already using #mui/material, you should use the one exported from #mui/material/styles so that the same theme is available for components from '#mui/material'.
So your Styles.tsx should be like:
import { Theme } from "#mui/system";
import { makeStyles } from "#mui/styles";
import { createTheme } from '#mui/material/styles';
//import muiTheme from "./constants/...";
export const useStyles = makeStyles((muiTheme) => ({
intro: {
padding: "0 2rem",
[theme.breakpoints.up("lg")]: {
padding: "0 4rem !important",
},
},
}));
And be aware:
⚠️ #mui/styles is the legacy styling solution for MUI. It depends on JSS as a styling solution, which is not used in the #mui/material anymore, deprecated in v5.
And
⚠️ #mui/styles is not compatible with React.StrictMode or React 18.
So I recommend using better solutions like styled or sx prop.

React app works on local but not when deployed

My app works perfectly in local, without errors, but when I try to deploy it on netlify or github pages, when I open it, the page is blank and many errors are displayed in the console.
The error says
TypeError: can't access property "length", e is undefined
where e corresponds to items (which is a state).
If I remove these lines of code, I get another error that always concerns items: the problem this time is with items.some, where items is null again.
Whatever I try to do items always result null.
I tried console.log(items) in many component files and in all of them the result is null.
This is the netlify link where you can see the error:
https://celadon-otter-917b4e.netlify.app/
Navbar.js, where the error is located:
import { Link } from 'react-router-dom';
import Searchbar from './Searchbar';
import { useContext } from 'react';
import FavoritesContext from '../FavoritesContext';
function Navbar() {
const { items } = useContext(FavoritesContext);
return (
<div className='navbar'>
<Link to={'/'} style={{ textDecoration: 'none' }}>
<div className='logo-container'>
<img src="/foglia.png" alt="logo" className='logo'/>
<h3>just<span>vegetables</span></h3>
</div>
</Link>
<Searchbar />
<Link to={'/favorites/'} style={{ textDecoration: 'none' }}>
<h4 className='favor'>Favorites: <span>{items.length}</span></h4>
</Link>
</div>
)
}
export default Navbar;
FavoriteContext.js:
import React, { createContext, useState, useEffect } from "react";
const FavoritesContext = createContext();
export function FavoritesProvider({ children }) {
const [ items, setItems ] = useState([]);
useEffect(() => {
const recipesFavorites = JSON.parse(localStorage.getItem('favorites-recipes'));
setItems(recipesFavorites);
}, []);
const saveToLocalStorage = (item) => {
localStorage.setItem('favorites-recipes', JSON.stringify(item))
}
const addToFavorites = (title, image, id, favorite) => {
if (!favorite) {
const newFavoriteList = [...items, { title, image, id }]
setItems(newFavoriteList);
saveToLocalStorage(newFavoriteList);
};
};
const removeFromFavorites = (title, image, id, favorite) => {
if (favorite) {
const newFavoriteList = items.filter((fav) => fav.id !== id);
setItems(newFavoriteList);
saveToLocalStorage(newFavoriteList);
};
};
return (
<FavoritesContext.Provider value={{ items, setItems, addToFavorites, removeFromFavorites }}>
{children}
</FavoritesContext.Provider>
)
}
export default FavoritesContext;
Card.js:
import { Link } from 'react-router-dom';
import FavoritesContext from '../FavoritesContext';
function Card({ title, image, id }) {
const { addToFavorites } = useContext(FavoritesContext);
const { removeFromFavorites } = useContext(FavoritesContext);
const { items } = useContext(FavoritesContext);
const checkIsAdd = () => {
if(items.some((val) => val.id === id)) {
return true;
}};
const [favorite, setFavorite] = useState(checkIsAdd);
const isInFavorites = (id) => {
return (
<img src='../cuore-pieno.png' alt="like" className='favorite blue' onClick={() => {removeFromFavorites(title, image, id, favorite); toggle()}}/>
)
}
const toggle = () => {
isInFavorites(id);
setFavorite(!favorite);
}
return (
<div className='card'>
{!favorite ? <img src='../cuore-vuoto.png' alt="like" className='favorite' onClick={() => {addToFavorites(title, image, id, favorite); toggle()}}/> : isInFavorites(id)}
<Link to={'/recipe/' + id}>
<img src={image} alt='' className='card-image'/>
<div className='card-info-cnt'>
<p className='card-title'>{title}</p>
</div>
</Link>
</div>
)
}
export default Card;
package.json
{
"name": "projetto-react",
"version": "0.1.0",
"homepage": "https://michela-z.github.io/justVegetables",
"main": "index.js",
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"lodash": "^4.17.21",
"node-env-webpack-plugin": "^1.1.0",
"process": "^0.11.10",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-icons": "^4.4.0",
"react-router-dom": "^6.3.0",
"react-scripts": "^5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d dist",
"serve": "webpack-dev-server --mode development --open --hot",
"start": "webpack-dev-server",
"build": "webpack --mode production",
"test": "react-scripts test",
"eject": "react-scripts eject",
"webpack": "webpack",
"webpack-dev-server": "webpack-dev-server",
"dev": "npm run webpack-dev-server -- --env mode=development",
"prod": "npm run webpack -- --env mode=production"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.18.13",
"#babel/preset-env": "^7.18.10",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^8.2.5",
"css-loader": "^6.7.1",
"file-loader": "^6.2.0",
"gh-pages": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"source-map-loader": "^4.0.0",
"url-loader": "^4.1.1",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.10.0"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const port = process.env.PORT || 3000;
module.exports = {
mode: 'development',
entry: {
index: {
import: './src/index.js',
dependOn: 'shared',
},
another: {
import: './src/another-module.js',
dependOn: 'shared',
},
shared: 'lodash',
},
output: {
filename: '[name].bundle.js',
path: path.join(__dirname, '/dist')
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
}
}
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource'
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
new webpack.ProvidePlugin({
process: 'process/browser',
}),
],
devServer: {
host: 'localhost',
port: port,
historyApiFallback: true,
open: true
},
optimization: {
runtimeChunk: 'single',
},
};
I'm new to programming, this is my first react app, I tried everything that was in my ability.
Check if there item present before checking its length {items.length}
you can achieve this by
{item && item.length} or
{items?.length}
this will get rid of the errors displayed in live deploy

TypeError: [setState with createContext] is not a function - React

I am using React's Context API to call setCurrentUser below. But it gives me this error:
TypeError: setCurrentUser is not a function.
Upon logging console.log(useContext(globalContext)), I get the empty object {}.
I have manually converted my project from TS(where it worked by specifying setCurrentUser as type Dispatch) to JS, so I am not sure if that broke something...at least my react and react-dom packages should be current.
How do we make this work with JS? Thanks
Router.jsx - where I am calling setCurrentUser
import React, { useContext, useEffect } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import LoginPg from "../pages/LoginPg/LoginPg";
import ErrorHandler from "./ErrorHandler";
import ErrorPg from "../pages/ErrorPg/ErrorPg";
import useGet from "../../server_api/useGet";
import ProtectedRoute from "./ProtectedRoute";
import HomePg from "../pages/HomePg/HomePg";
import { globalContext } from "../../store/context/globalContext";
import CalendarPg from "../pages/Calendar/CalendarPg";
function Router() {
const { currentUser, setCurrentUser } = useContext(globalContext);
const [doGet] = useGet();
let user;
console.log(useContext(globalContext)); // <==== logs: {}
useEffect(() => {
doGet("auth/authenticate", (res) => {
if (res) {
user = res.username;
setCurrentUser(res);
} else {
console.log("Router: user not authenticated");
}
});
}, []);
return (
<BrowserRouter>
<ErrorHandler>
<Switch>
<Route path="/error" component={ErrorPg} />
<Route path="/login" component={LoginPg} />
<ProtectedRoute
path="/calendar"
Component={CalendarPg}
isAuth={currentUser}
key="uniquevalue"
/>
<ProtectedRoute path="/" Component={HomePg} isAuth={currentUser} />
</Switch>
</ErrorHandler>
</BrowserRouter>
);
}
export default Router;
globalContext.jsx
import { createContext, useState } from "react";
export const globalContext = createContext({});
export default function GlobalContext(props) {
const [currentUser, setCurrentUser] = useState(null);
return (
<globalContext.Provider value={{ currentUser, setCurrentUser }}>
{props.children}
</globalContext.Provider>
);
}
package.json
{
"name": "test",
"version": "0.1.0",
"private": true,
"homepage": "/",
"dependencies": {
"#fullcalendar/daygrid": "^5.9.0",
"#fullcalendar/interaction": "^5.9.0",
"#fullcalendar/react": "^5.9.0",
"#fullcalendar/timegrid": "^5.9.0",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"antd": "^4.16.13",
"axios": "^0.21.1",
"bootstrap": "^5.1.1",
"font-awesome": "^4.7.0",
"fullcalendar": "^5.9.0",
"lodash": "^4.17.21",
"moment": "^2.29.1",
"query-string": "^4.3.4",
"react": "^17.0.2",
"react-calendar": "^3.4.0",
"react-dom": "^17.0.2",
"react-helmet": "^6.1.0",
"react-modal": "^3.14.3",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"sass": "^1.39.2",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"cypress": "npx cypress open"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"cypress": "^7.5.0"
}
}
You need the consumer (Router) to be a child of the provider (GlobalContext).
Also your component names should start with an Upper case.
import { GlobalContext } from "../../store/context/GlobalContext";
const App = () => {
const [currentUser, setCurrentUser] = useState(DEFAULT_USER);
return (
<GlobalContext.Provider value={{ currentUser, setCurrentUser }}>
<Router />
</GlobalContext.Provider>
);
};

React redux store isn't connecting

I'm connecting store to my react application, But it gives me error TypeError: state is undefined
store/index.js(Creating Reducer function)
import {createStore} from 'redux';
const counterReducer = (state:{counter:0},action) => {
if(action.type==='increment')
{
return {
counter: state.counter + 1
}
}
if (action.type === 'decrement') {
return {
counter: state.counter - 1
}
}
return state;
}
const store = createStore(counterReducer);
export default store;
main index.js(Main index of my file)
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import store from './store/index';
import './index.css';
import App from './App';
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
Now I'm using my Counter components like this:(src/components/Counter.js)
import classes from './Counter.module.css';
import {useSelector} from 'react-redux';
const Counter = () => {
const counter = useSelector(state => state.counter);
const toggleCounterHandler = () => {};
return (
<main className={classes.counter}>
<h1>Redux Counter</h1>
<div className={classes.value}>{counter}</div>
<button onClick={toggleCounterHandler}>Toggle Counter</button>
</main>
);
};
export default Counter;
here is my package.json:
{
"name": "redux-basics",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.11.9",
"#testing-library/react": "^11.2.5",
"#testing-library/user-event": "^12.6.3",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-redux": "^7.2.4",
"react-scripts": "4.0.2",
"redux": "^4.1.0",
"web-vitals": "^1.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Error:
TypeError: state is undefined
Counter/counter<
C:/Users/nikku/Desktop/redux-project/src/components/Counter.js:6
3 |
4 |
5 | const Counter = () => {
> 6 | const counter = useSelector((state) => state.counter);
7 | const toggleCounterHandler = () => {};
8 |
9 | return (
useSelector should get state as argument by default right? but here it is saying it is undefined. Ca you please share you thoughts? Did I do something wrong ?
In order to initialize a default state, you need to use the = assignment operator
const counterReducer = (state = {counter:0},action) => {
Default state is initialized like this. This will fix your issue.
function appReducer(state = MyInitialState, action) {
switch (action.type) {
case "my_custom_type":
return {
...state
};
default:
return state;
}
}

react i18next hasLoadedNamespace: i18next was not initialized undefined

Yarn start causes intermittent errors.
No correction has been made to the code that is causing the error.
It is also common to save and recompile code from other files.
Once in a while you can render without any problems.
Error
Error image
Console alert image
TypeError: t(...).map is not a function
*Please check the image.
I made a map of the json file that i18next uses to translate.
i18next: hasLoadedNamespace: i18next was not initialized undefined
,
key "about" for languages "en" won't get resolved as namespace "header" was not yet loaded This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!! is printed from the console with the error mentioned earlier.
Package.json
{
"name": "homepage",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"#types/i18next": "^13.0.0",
"#types/react-i18next": "^8.1.0",
"i18next": "^19.8.4",
"i18next-xhr-backend": "^3.2.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-i18next": "^11.7.4",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.1",
"styled-components": "^5.2.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#types/react": "^17.0.0",
"#types/react-router-dom": "^5.1.6",
"#types/styled-components": "^5.1.4",
"#typescript-eslint/eslint-plugin": "^4.9.0",
"#typescript-eslint/parser": "^4.9.0",
"eslint": "^7.14.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-config-airbnb-typescript": "^12.0.0",
"eslint-config-prettier": "^6.15.0",
"eslint-config-react-app": "^6.0.0",
"eslint-import-resolver-alias": "^1.1.2",
"eslint-import-resolver-typescript": "^2.3.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-flowtype": "^5.2.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-react": "^7.21.5",
"eslint-plugin-react-hooks": "^4.2.0",
"prettier": "^2.2.1",
"prettier-eslint": "^12.0.0",
"prettier-eslint-cli": "^5.0.0"
}
}
Dir
root
|-public
| |-locales
| |-productWS
| |-en.json
| |-ko.json
|-src
| |-components
| | |-MwsCard.tsx
| |-systems
| | |-ProductWs.ts
| |-i18n.ts
en.json
{
"miniTitle":"ABC",
"title":"ABCDEFG",
"text": "abcdefg",
"version":[
{
"name": "1",
"sensor": ["1", "2", "3", "4", "5"],
"src":"/img/1.jpg"
},
{
"name": "2",
"sensor": ["1", "2", "3", "4", "5", "6", "7"],
"src":"/img/2.jpg"
}
]
}
ProductWs.tsx
import React from 'react';
import { useTranslation } from 'react-i18next';
import { MwsCard } from '../../components';
import { Wrap, Container, TitleH5, TitleH2, TextP1, CardContainer } from './ProductWsStyle';
interface VersionProps {
name: string;
sensor: string[];
src: string;
}
function ProductWs() {
const { t } = useTranslation('productWsDB');
return (
<Wrap>
<Container>
<TitleH5>{t('miniTitle')}</TitleH5>
<TitleH2>{t('title')}</TitleH2>
<TextP1>{t('text')}</TextP1>
<CardContainer>
****Error point---------------
{t<VersionProps[]>('version', { returnObjects: true }).map(item => (
<MwsCard key={item.name} name={item.name} sensor={item.sensor} src={item.src} />
))}
****Error point---------------
</CardContainer>
</Container>
</Wrap>
);
}
export default ProductWs;
MwsCard.tsx
import React from 'react';
import * as S from './MwsCardStyle';
import { Version } from './MwsProdDBType';
function MwsCard({ name, sensor, src }: Version) {
return (
<S.Container>
<S.Img src={src} alt={name} />
<S.Info>
<S.Title>{name}</S.Title>
{sensor.map(item => (
<S.Spec key={item}>{item}</S.Spec>
))}
</S.Info>
</S.Container>
);
}
export default MwsCard;
i18n.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import backend from 'i18next-xhr-backend';
const userLanguage = window.navigator.language;
i18n
.use(backend)
.use(initReactI18next)
.init({
lng: localStorage.getItem('language') || userLanguage || 'en',
fallbackLng: 'en',
debug: true,
keySeparator: '.',
interpolation: {
escapeValue: false,
},
react: {
wait: true,
useSuspense: false,
},
backend: {
loadPath: '/locales/{{ns}}/{{lng}}.json',
},
});
export default i18n;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './i18n';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root'),
);
reportWebVitals();
app.js
import React, { Suspense } from 'react';
import Routes from './Routes';
import Theme from './global-styles/Theme';
import './global-styles/import-fonts.css';
import { GlobalStyle } from './global-styles/GlobalStyle';
function App() {
return (
<Suspense fallback={<div>Loading...</div>} maxDuration={5000}>
<Theme>
<GlobalStyle />
<Routes />
</Theme>
</Suspense>
);
}
export default App;
You need to add the i18next provider into your react tree.
import React from 'react';
import ReactDOM from 'react-dom';
import { I18nextProvider } from 'react-i18next';
import './i18n';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<I18nextProvider i18n={i18n}>
// ---^
<App />
</I18nextProvider>
</React.StrictMode>,
document.getElementById('root'),
);
reportWebVitals();

Categories