Server Error ReferenceError: window is not defined This error happened while generating the page - javascript

I want to add Microsoft Login Button in Next Js using material Ui but
when I add package from NPM and refresh the page I got the above
error.
When I Assign ClientId="a973536f-eb3e-4fd9-9394-9f4194d69153" to Microsoft component as shown below I got the above error. How to cope with this error.
import React from "react";
import { Grid, Container, Checkbox, IconButton, FormControlLabel, TextField, Button, Link } from "#material-ui/core";
import { makeStyles } from "#material-ui/core/styles";
import Icon from "#material-ui/core/Icon";
import { loadCSS } from "fg-loadcss";
import FacebookLogin from "react-facebook-login/dist/facebook-login-render-props";
import { GoogleLogin } from "react-google-login";
import MicrosoftLogin from "react-microsoft-login";
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(0),
display: "flex",
flexDirection: "column",
alignItems: "center",
height: '60vh',
},
background: {
backgroundColor: "#220E1A",
borderRadius: "5px",
color: "white",import React from "react";
import { Grid, Container, Checkbox, IconButton, FormControlLabel, TextField, Button, Link } from "#material-ui/core";
import { makeStyles } from "#material-ui/core/styles";
import Icon from "#material-ui/core/Icon";
import { loadCSS } from "fg-loadcss";
import FacebookLogin from "react-facebook-login/dist/facebook-login-render-props";
import { GoogleLogin } from "react-google-login";
import MicrosoftLogin from "react-microsoft-login";
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(0),
display: "flex",
flexDirection: "column",
alignItems: "center",
height: '60vh',
},
background: {
backgroundColor: "#220E1A",
borderRadius: "5px",
color: "white",
},
form: {
width: "70%", // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
input1: {
background: "white",
borderRadius: "25px",
color: "white",
},
submit: {
margin: theme.spacing(1, 0, 1),
borderRadius: "25px",
},
buttonGroup: {
borderRadius: "50px",
margin: theme.spacing(2, 0, 2, 0),
},
winIcon: {
padding: '0px',
margin: '0px',
width: '10px'
}
}));
export default function SignIn() {
const classes = useStyles();
//Load Fonts awesome icons
React.useEffect(() => {
const node = loadCSS(
"https://use.fontawesome.com/releases/v5.12.0/css/all.css",
document.querySelector("#font-awesome-css")
);
return () => {
node.parentNode.removeChild(node);
};
}, []);
//google facebook,Microsoft Login response
const responseFacebook = (response) => {
console.log(response);
};
const responseGoogle = (response) => {
console.log(response);
};
const authHandler = (err, data) => {
console.log(err, data);
};
return (
<Container maxWidth="xm" className={classes.background}>
<div className={classes.paper}>
<form className={classes.form} noValidate>
<TextField
className={classes.input1}
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoFocus
variant="filled"
/>
<TextField
className={classes.input1}
variant="filled"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<Grid
container
direction="column"
justify="center"
alignItems="center"
>
<Grid item >
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Stay signed in"
/>
</Grid>
<Grid item>
<Button
type="submit"
medium
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
</Grid>
<Grid item>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<h3 align="center">Or Via</h3>{" "}
<FacebookLogin
appId="225241158739281"
autoLoad
callback={responseFacebook}
render={(renderProps) => (
<IconButton color="primary" onClick={renderProps.onClick}>
<Icon className="fab fa-facebook" />
</IconButton>
)}
/>
<GoogleLogin
clientId="500452257814-peb71oi9612hv04svvfpvfrtch6pc5br.apps.googleusercontent.com"
render={(renderProps) => (
<IconButton
onClick={renderProps.onClick}
>
{" "}
<Icon className="fab fa-google" color="primary" />
</IconButton>
)}
buttonText="Login"
onSuccess={responseGoogle}
onFailure={responseGoogle}
cookiePolicy={"single_host_origin"}
/>
//**Problem is here IN MicrosoftLogin when i assign Id it creates the above error.**
<MicrosoftLogin
// clientId="a973536f-eb3e-4fd9-9394-9f4194d69153"
authCallback={authHandler}
redirectUri="https://localhost:3000/"
className={classes.winIcon}
children={
<IconButton>
<Icon className="fab fa-windows" color="primary" />
</IconButton>}
/>
</Grid>
</Grid>
</form>
</div>
</Container>
);
}
},
form: {
width: "70%", // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
input1: {
background: "white",
borderRadius: "25px",
color: "white",
},
submit: {
margin: theme.spacing(1, 0, 1),
borderRadius: "25px",
},
buttonGroup: {
borderRadius: "50px",
margin: theme.spacing(2, 0, 2, 0),
},
winIcon: {
padding: '0px',
margin: '0px',
width: '10px'
}
}));
export default function SignIn() {
const classes = useStyles();
//Load Fonts awesome icons
React.useEffect(() => {
const node = loadCSS(
"https://use.fontawesome.com/releases/v5.12.0/css/all.css",
document.querySelector("#font-awesome-css")
);
return () => {
node.parentNode.removeChild(node);
};
}, []);
//google facebook,Microsoft Login response
const responseFacebook = (response) => {
console.log(response);
};
const responseGoogle = (response) => {
console.log(response);
};
const authHandler = (err, data) => {
console.log(err, data);
};
return (
<Container maxWidth="xm" className={classes.background}>
<div className={classes.paper}>
<form className={classes.form} noValidate>
<TextField
className={classes.input1}
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoFocus
variant="filled"
/>
<TextField
className={classes.input1}
variant="filled"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<Grid
container
direction="column"
justify="center"
alignItems="center"
>
<Grid item >
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Stay signed in"
/>
</Grid>
<Grid item>
<Button
type="submit"
medium
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
</Grid>
<Grid item>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<h3 align="center">Or Via</h3>{" "}
<FacebookLogin
appId="225241158739281"
autoLoad
callback={responseFacebook}
render={(renderProps) => (
<IconButton color="primary" onClick={renderProps.onClick}>
<Icon className="fab fa-facebook" />
</IconButton>
)}
/>
<GoogleLogin
clientId="500452257814-peb71oi9612hv04svvfpvfrtch6pc5br.apps.googleusercontent.com"
render={(renderProps) => (
<IconButton
onClick={renderProps.onClick}
>
{" "}
<Icon className="fab fa-google" color="primary" />
</IconButton>
)}
buttonText="Login"
onSuccess={responseGoogle}
onFailure={responseGoogle}
cookiePolicy={"single_host_origin"}
/>
//**Problem is here IN MicrosoftLogin when i assign Id it creates the above error.**
<MicrosoftLogin
// clientId="a973536f-eb3e-4fd9-9394-9f4194d69153"
authCallback={authHandler}
redirectUri="https://localhost:3000/"
className={classes.winIcon}
children={
<IconButton>
<Icon className="fab fa-windows" color="primary" />
</IconButton>}
/>
</Grid>
</Grid>
</form>
</div>
</Container>
);
}

It's related to server side rendering and client side rendering.
As Next.js provides SSR, you need to consider using objects like window, localStorage and so on. While compiling client side, those objects are fine but when Nextjs compiles server side, it shows error like you shared.
It seems like GoogleLogin uses window object if you assign the client id. You need to check that first. And lemme know the result.

Hey the easy way for Material UI Components, to rendered it on Next js framework.Just use component to render it on client side only.
(If any component use Window object on server side it will show this error)
solution:
import NoSsr from '#material-ui/core/NoSsr';
<NoSsr>
<MicrosoftLogin
clientId="a973536f-eb3e-4fd9-9394-9f4194d69153"
authCallback={authHandler}
redirectUri="https://localhost:3000/"
className={classes.winIcon}
children={
<IconButton>
<Icon className="fab fa-windows" color="primary" />
</IconButton>
}
/>
</NoSsr>

Related

why i always get this cors error, using cpanel, laravel, reactjs

i always get this error
"Access to XMLHttpRequest at 'http://localhost:8000/sanctum/csrf-cookie' from origin 'http://kekean.pusproset.site' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space local."
the error said that the origin doesnt match, but i already changed the baseURL in the axios to match my wesite url. here's my navs.js file
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Main from './container/Main'
import CatalogPage from './container/CatalogPage';
import Navbar from './components/Navbar'
import CssBaseline from '#mui/material/CssBaseline'
import { createTheme, ThemeProvider } from '#mui/material/styles'
import ProductPage from './container/ProductPage';
import Payment from './container/Payment';
import LoginPage from './container/LoginPage';
import RegisterPage from './container/RegisterPage';
import axios from 'axios';
function Navs() {
const catalog = JSON.parse(JSON.stringify(require('./catalog.json')))
const theme = createTheme({
palette: {
primary: {
main: "#FF674D"
},
secondary: {
main: "#7776BC"
},
subtitle : "rgb(0, 0, 0, 31%)"
},
typography: {
"fontFamily": `"Poppins", "Helvetica", "Arial", sans-serif`,
"fontSize": 14,
"fontWeightLight": 300,
"fontWeightRegular": 400,
"fontWeightMedium": 500,
button: {
textTransform: 'none'
}
},
shape: {
borderRadius: 12,
},
breakpoints: {
values: {
mobile: 0,
tablet: 640,
laptop: 1024,
desktop: 1200,
},
},
})
axios.defaults.baseURL = "http://kekean.pusproset.site/";
axios.defaults.headers.post['Accept'] = "application/json";
axios.defaults.headers.post['Content-Type'] = "application/json";
axios.defaults.withCredentials = true;
return (
<ThemeProvider theme={theme}>
<CssBaseline/>
<Router>
<Navbar/>
<Routes>
<Route path="/" exact element={<Main/>}/>
<Route path="/catalog" element={<CatalogPage/>}/>
<Route path='/products/:productId' element={<ProductPage/>}/>
<Route path='/payment' element={<Payment/>}/>
<Route path='/login' element={<LoginPage/>}/>
<Route path='/register' element={<RegisterPage/>}/>
</Routes>
</Router>
</ThemeProvider>
);
}
export default Navs;
if (document.getElementById('app')) {
ReactDOM.render(<Navs/>, document.getElementById('app'));
}
here's my registerPage.js that uses the axios csrf
import {
Box,
Typography,
Grid,
FilledInput,
FormControl,
InputLabel,
Button,
FormHelperText,
} from "#mui/material";
import { makeStyles } from "#mui/styles";
import axios from "axios";
import React from "react";
import swal from "sweetalert";
import { useNavigate } from 'react-router-dom'
const useStyles = makeStyles((theme) => ({
root: {
borderRadius: 10,
},
input: {
"&:-webkit-autofill": {
borderRadius: 10,
},
},
}));
function RegisterPage() {
const history = useNavigate()
const [register, setRegister] = React.useState({
first_name: "",
last_name: "",
address: "",
email: "",
password: "",
number_phone: '',
error_list: [],
});
const handleInput = (e) => {
e.persist();
setRegister({ ...register, [e.target.name]: e.target.value });
};
const registerSubmit = (e) => {
e.preventDefault();
const data = {
first_name: register.first_name,
last_name: register.last_name,
address: register.address,
email: register.email,
password: register.password,
number_phone: register.number_phone,
};
axios.get("/sanctum/csrf-cookie").then((response) => {
axios
.post('/api/register', data)
.then((res) => {
if(res.data.status === 200) {
localStorage.setItem('auth_token', res.data.token)
localStorage.setItem('auth_firstName', res.data.first_name)
swal('Success', res.data.message, "success")
history.push('/')
} else {
setRegister({...register, error_list: res.data.validation_errors})
}
});
});
};
const classes = useStyles();
return (
<Box
display="flex"
justifyContent="center"
alignItems="center"
minHeight="85vh"
>
<Box
textAlign={"center"}
sx={{ border: "1px solid #CACACA", borderRadius: "16px" }}
p={3}
>
<Typography fontSize={"28px"}>
Daftar untuk belanja
<Box
component={"span"}
sx={{ color: "#FF674D", fontSize: "36px" }}
>
.
</Box>
</Typography>
<Typography color="#939393" fontSize={"12px"}>
Sudah punya akun?{" "}
<Box
component={"span"}
sx={{ color: "#FF674D", fontSize: "12px" }}
>
Masuk Sekarang
</Box>
</Typography>
<form onSubmit={registerSubmit}>
<Grid container sx={{ maxWidth: 450, mt: 2 }} spacing={2}>
<Grid item mobile={6}>
<FormControl error={register.error_list.first_name?true:false} fullWidth variant="filled">
<InputLabel htmlFor="component-filled">
First Name
</InputLabel>
<FilledInput
id="component-filled"
disableUnderline={true}
onChange={handleInput}
name="first_name"
value={register.first_name}
classes={{
root: classes.root,
input: classes.input,
}}
/>
<FormHelperText sx={{fontSize: 10}}>{register.error_list.first_name}</FormHelperText>
</FormControl>
</Grid>
<Grid item mobile={6}>
<FormControl error={register.error_list.last_name?true:false} fullWidth variant="filled">
<InputLabel htmlFor="component-filled">
Last Name
</InputLabel>
<FilledInput
id="component-filled"
disableUnderline={true}
onChange={handleInput}
value={register.last_name}
name="last_name"
classes={{
root: classes.root,
input: classes.input,
}}
/>
<FormHelperText sx={{fontSize: 10}}>{register.error_list.last_name}</FormHelperText>
</FormControl>
</Grid>
<Grid item mobile={12}>
<FormControl error={register.error_list.address?true:false} fullWidth variant="filled">
<InputLabel htmlFor="component-filled">
Address
</InputLabel>
<FilledInput
id="component-filled"
disableUnderline={true}
onChange={handleInput}
value={register.address}
name="address"
classes={{
root: classes.root,
input: classes.input,
}}
/>
<FormHelperText>{register.error_list.address}</FormHelperText>
</FormControl>
</Grid>
<Grid item mobile={12}>
<FormControl error={register.error_list.number_phone?true:false} fullWidth variant="filled">
<InputLabel htmlFor="component-filled">
Phone Number
</InputLabel>
<FilledInput
id="component-filled"
disableUnderline={true}
onChange={handleInput}
value={register.number_phone}
name="number_phone"
classes={{
root: classes.root,
input: classes.input,
}}
/>
<FormHelperText>{register.error_list.number_phone}</FormHelperText>
</FormControl>
</Grid>
<Grid item mobile={12}>
<FormControl error={register.error_list.email?true:false} fullWidth variant="filled">
<InputLabel htmlFor="component-filled">
Email
</InputLabel>
<FilledInput
id="component-filled"
disableUnderline={true}
value={register.email}
onChange={handleInput}
name="email"
classes={{
root: classes.root,
input: classes.input,
}}
/>
<FormHelperText>{register.error_list.email}</FormHelperText>
</FormControl>
</Grid>
<Grid item mobile={12}>
<FormControl error={register.error_list.password?true:false} fullWidth variant="filled">
<InputLabel htmlFor="component-filled">
Password
</InputLabel>
<FilledInput
id="component-filled"
disableUnderline={true}
onChange={handleInput}
value={register.password}
type="password"
name="password"
classes={{
root: classes.root,
input: classes.input,
}}
/>
<FormHelperText>{register.error_list.password}</FormHelperText>
</FormControl>
</Grid>
<Grid item mobile={12}>
<FormControl error={register.error_list.password?true:false} fullWidth variant="filled">
<InputLabel htmlFor="component-filled">
Confirm Password
</InputLabel>
<FilledInput
id="component-filled"
disableUnderline={true}
onChange={handleInput}
type="password"
name="confirmPassword"
classes={{
root: classes.root,
input: classes.input,
}}
/>
</FormControl>
</Grid>
</Grid>
<Box
display="flex"
justifyContent="center"
alignItems="center"
>
<Button
type="submit"
variant="contained"
disableElevation={true}
sx={{ mt: 3, mr: 2 }}
>
<Typography color="white" sx={{ px: 6, py: 1 }}>
Daftar
</Typography>
</Button>
</Box>
</form>
</Box>
</Box>
);
}
export default RegisterPage;

How to create new components on every button click in "React"

So I want when the user clicks on the button, be able to create new CatagoryField Component that I made. When I place the component in a function and call it it will only create the component once. I will appreciate some help. I'm confused about how should I implement this?
App components
import React, { useState } from "react";
import {
Accordion,
AccordionSummary,
Chip,
Button,
IconButton,
Autocomplete,
TextField,
} from "#mui/material";
import { Grid } from "#mui/material";
import SearchBar from "material-ui-search-bar";
import DeleteIcon from "#mui/icons-material/Delete";
import ExpandMoreOutlinedIcon from "#mui/icons-material/ExpandMoreOutlined";
import AddCircleOutlineOutlinedIcon from "#mui/icons-material/AddCircleOutlineOutlined";
import HelpIcon from "#mui/icons-material/Help";
import HistoryToggleOffIcon from "#mui/icons-material/HistoryToggleOff";
import AllMembers from "./components/common/main/allMembers";
import CatagoryField from "./components/common/main/catagoryField";
const autoCompleteOptions = [
{ title: "A", year: 1994 },
{ title: "B", year: 1972 },
{ title: "C", year: 1974 },
{ title: "D", year: 2008 },
{ title: "E", year: 1957 },
{ title: "F", year: 1993 },
{ title: "G", year: 1994 },
];
const App = () => {
const [value, setValue] = useState();
const [element, setElement] = useState(0);
const doSomethingWith = () => {
return null;
};
let i = 0;
const creator = () => {
while (i < element) {
i++;
return (
<CatagoryField
catagoryName="خدماتی"
react="از آنها چیزی میخریم"
createdBy="سیستم"
disable={false}
/>
);
}
};
console.log(element);
return (
<>
<div style={{ margin: "4rem 1rem" }}>
<Accordion>
<AccordionSummary
sx={{ height: "65px" }}
aria-controls="panel1a-content"
>
<Grid
container
direction="row"
justifyContent="space-between"
alignItems="center"
>
<Grid item>
<IconButton className="chevron__icon">
<ExpandMoreOutlinedIcon />
</IconButton>
<span className="users__catagory"> دسته بندی کاربران</span>
</Grid>
<Grid item>
<IconButton>
<HistoryToggleOffIcon />
</IconButton>
<IconButton>
<HelpIcon className="help" />
</IconButton>
<span className="version">4.3.2</span>
</Grid>
</Grid>
</AccordionSummary>
<AccordionSummary
sx={{
height: "65px",
padding: "30px",
background: "#E6E6E6",
cursor: "default !important",
}}
aria-controls="panel1a-content"
>
<Grid
container
direction="row"
alignItems="center"
sx={{ display: "relative" }}
>
<Grid item>
<Button
variant="outlined"
sx={{ height: "50px" }}
size="medium"
onClick={() => setElement(element + 1)}
endIcon={
<AddCircleOutlineOutlinedIcon
sx={{ marginRight: "10px" }}
/>
}
>
افزودن دسته جدید
</Button>
</Grid>
<Grid sx={{ width: "207px" }} item>
<SearchBar
className="search__holder"
placeholder="جستجو..."
value={value}
style={{ width: "207px", height: "45px" }}
onChange={(newValue) => setValue(newValue)}
onRequestSearch={() => doSomethingWith()}
/>
</Grid>
<Grid className="sort__field" item>
<Autocomplete
sx={{
width: "207px !important",
padding: "0 !important",
backgroundColor: "white !important",
}}
options={autoCompleteOptions}
getOptionLabel={(option) => option.title}
renderTags={(value, getTagProps) =>
value.map((option, index) => (
<Chip
variant="outlined"
label={option.title}
{...getTagProps({ index })}
/>
))
}
renderInput={(params) => (
<TextField
{...params}
variant="filled"
sx={{
width: "207px !important",
padding: "0 !important",
background: "white !important",
}}
placeholder="مرتب سازی..."
/>
)}
/>
</Grid>
<Grid item>
<IconButton sx={{ margin: "0 5px" }}>
<DeleteIcon />
</IconButton>
</Grid>
<Grid item className="last__edit">
<Grid item>
<span>
آخرین ویرایش:
<a className="last_Modified" href="#">
سیستم
</a>
</span>
<span>1405/12/24 23:59 </span>
</Grid>
</Grid>
</Grid>
</AccordionSummary>
<AllMembers />
<CatagoryField
catagoryName="اپراتور سیستم"
react="اپراتور سیستم"
createdBy="سیستم"
/>
<CatagoryField
catagoryName="مشتریان"
react="به آنها چیزی فروخته ایم"
createdBy="سیستم"
/>
<CatagoryField
catagoryName="خدماتی"
react="از آنها چیزی میخریم"
createdBy="سیستم"
disable={false}
/>
{creator()}
</Accordion>
</div>
</>
);
};
export default App;
The best way in order to achieve the solution is to use a state with useMemo.and the problem with your code is that the creator acts as a function and it will only execute once try this.
import {useMemo} from 'react';
const App = () => {
const [elements , setElements] = useState(0);
const creator = useMemo(() => {
return (
<>
{Array(elements).fill(elements).map((item , index) => (
<CategoryField
key={`cat-${index}`} // key is need when mapping! it is not props
catagoryName="خدماتی"
react="از آنها چیزی میخریم"
createdBy="سیستم"
disable={false}
/>
))}
</>
)
},[elements]);//render when elements change
return (
<>
<div style={{ margin: "4rem 1rem" }}>
<Accordion>
<AccordionSummary
sx={{ height: "65px" }}
aria-controls="panel1a-content"
>
<Grid
container
direction="row"
justifyContent="space-between"
alignItems="center"
>
<Grid item>
<IconButton className="chevron__icon">
<ExpandMoreOutlinedIcon />
</IconButton>
<span className="users__catagory"> دسته بندی کاربران</span>
</Grid>
<Grid item>
<IconButton>
<HistoryToggleOffIcon />
</IconButton>
<IconButton>
<HelpIcon className="help" />
</IconButton>
<span className="version">4.3.2</span>
</Grid>
</Grid>
</AccordionSummary>
<AccordionSummary
sx={{
height: "65px",
padding: "30px",
background: "#E6E6E6",
cursor: "default !important",
}}
aria-controls="panel1a-content"
>
<Grid
container
direction="row"
alignItems="center"
sx={{ display: "relative" }}
>
<Grid item>
<Button
variant="outlined"
sx={{ height: "50px" }}
size="medium"
onClick={() => setElements(elements + 1)}
endIcon={
<AddCircleOutlineOutlinedIcon
sx={{ marginRight: "10px" }}
/>
}
>
افزودن دسته جدید
</Button>
</Grid>
<Grid sx={{ width: "207px" }} item>
<SearchBar
className="search__holder"
placeholder="جستجو..."
value={value}
style={{ width: "207px", height: "45px" }}
onChange={(newValue) => setValue(newValue)}
onRequestSearch={() => doSomethingWith()}
/>
</Grid>
<Grid className="sort__field" item>
<Autocomplete
sx={{
width: "207px !important",
padding: "0 !important",
backgroundColor: "white !important",
}}
options={autoCompleteOptions}
getOptionLabel={(option) => option.title}
renderTags={(value, getTagProps) =>
value.map((option, index) => (
<Chip
key={`chip-${index}`}
variant="outlined"
label={option.title}
{...getTagProps({ index })}
/>
))
}
renderInput={(params) => (
<TextField
{...params}
variant="filled"
sx={{
width: "207px !important",
padding: "0 !important",
background: "white !important",
}}
placeholder="مرتب سازی..."
/>
)}
/>
</Grid>
<Grid item>
<IconButton sx={{ margin: "0 5px" }}>
<DeleteIcon />
</IconButton>
</Grid>
<Grid item className="last__edit">
<Grid item>
<span>
آخرین ویرایش:
<a className="last_Modified" href="#">
سیستم
</a>
</span>
<span>1405/12/24 23:59 </span>
</Grid>
</Grid>
</Grid>
</AccordionSummary>
<AllMembers />
<CatagoryField
catagoryName="اپراتور سیستم"
react="اپراتور سیستم"
createdBy="سیستم"
/>
<CatagoryField
catagoryName="مشتریان"
react="به آنها چیزی فروخته ایم"
createdBy="سیستم"
/>
<CatagoryField
catagoryName="خدماتی"
react="از آنها چیزی میخریم"
createdBy="سیستم"
disable={false}
/>
{creator}
</Accordion>
</div>
</>
);
}
export default App;

I have a javascript error in react js project

I've tried many things and there's no way, always appears this error I tried to use only one option to see if passed, changed the call of jquery, but not.
I looked in various places on the internet about this error, but could not solve or understand why it is happening.
Syntax Error: unexpected token <
Here is my code:
import * as React from 'react';
import Avatar from '#mui/material/Avatar';
import Button from '#mui/material/Button';
import CssBaseline from '#mui/material/CssBaseline';
import TextField from '#mui/material/TextField';
import FormControlLabel from '#mui/material/FormControlLabel';
import Checkbox from '#mui/material/Checkbox';
import Link from '#mui/material/Link';
import Grid from '#mui/material/Grid';
import Box from '#mui/material/Box';
import LockOutlinedIcon from '#mui/icons-material/LockOutlined';
import Typography from '#mui/material/Typography';
import Container from '#mui/material/Container';
import { createTheme, ThemeProvider } from '#mui/material/styles';
function Copyright(props) {
return (
<Typography variant="body2" color="text.secondary" align="center" {...props}>
{'Copyright © '}
<Link color="inherit" href="https://mui.com/">
Your Website
</Link>{' '}
{new Date().getFullYear()}
{'.'}
</Typography>
);
}
const theme = createTheme();
export default function SignIn() {
const handleSubmit = (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
console.log({
email: data.get('email'),
password: data.get('password'),
});
};
return (
<ThemeProvider theme={theme}>
<Container component="main" maxWidth="xs">
<CssBaseline />
<Box
sx={{
marginTop: 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
<TextField
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
/>
<TextField
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link href="#" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</Box>
</Box>
<Copyright sx={{ mt: 8, mb: 4 }} />
</Container>
</ThemeProvider>
);
}

React native invariant violation: text strings must be rendered within a <Text> component in a form (TextField)

This is my code for a form in React Native which is where i seem to be getting the error. I'm confused as this renders perfectly fine in my web simulator (expo):
working form but I get this error when I use ios simulator. I don't have any conditional logic or spaces/semicolons(at least what i can find) so not sure why I'm getting this error, also i'm using material ui core for my text fields in my form (which is where the error is supposedly coming from if you ref the image above). Any help would be appreciated!! pls help
import React, { useRef, useState } from 'react'
import { StyleSheet, View, Text, Modal } from 'react-native';
import { Formik, Form, FieldArray } from 'formik';
import { makeStyles } from '#material-ui/core/styles';
import { Button, TextField } from "#material-ui/core";
import { recipeService } from '../services/RecipeService';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
flexWrap: 'wrap',
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
marginTop: theme.spacing(1),
},
}));
export default function NewRecipe({ route }) {
const [showAlert, setShowAlert] = useState(false);
const { userId } = route.params;
const instructions = [''];
const ingredients = [{ name: '', amount: '', optional: false }];
const classes = useStyles();
const input = useRef();
return (
<View style={styles.container}>
<Formik
initialValues={{ userId: userId, name: "", summary: "", instructions: instructions, ingredients: ingredients }}
onSubmit={(values, actions) => {
recipeService.createRecipe(values).then(
(response) => {
console.log(response);
setShowAlert(true);
console.log("alert = " + showAlert);
actions.resetForm({});
return (
<Modal
animationType="slide"
transparent={false}
visible={true}
onRequestClose={
() => { setShowAlert(false); }
}>
<View style={styles.modalView}>
<Text>Recipe saved!</Text>
<Button
margin="normal"
type="button"
variant="contained"
color="default"
className={classes.textField}
onClick={() => actions.resetForm({})}
>
New Recipe
</Button>
</View>
</Modal>
)
}
)
.catch((error) => {
console.log(error);
});
}
}
>{({ values, handleChange, handleBlur }) => (
<Form>
<TextField
fullWidth
variant="outlined"
id="name"
name="name"
label="Name"
value={values.name}
onChange={handleChange}
/>
<TextField
fullWidth
multiline
variant="outlined"
id="summary"
name="summary"
label="Summary"
className={classes.textField}
value={values.summary}
onChange={handleChange}
/>
<View style={styles.row}>
<FieldArray
name="ingredients"
render={arrayHelpers => (
<div>
{values.ingredients.map((item, index) => (
<div key={index}>
<TextField
variant="outlined"
label="Ingredient Name"
name={`ingredients.${index}.name`}
value={item.name}
margin="normal"
className={classes.textField}
onChange={handleChange}
style={{ margin: 8, width: 233 }}
onBlur={handleBlur}
/>
<TextField
variant="outlined"
label="Amount"
name={`ingredients.${index}.amount`}
value={item.amount}
margin="normal"
className={classes.textField}
onChange={handleChange}
style={{ margin: 8, width: 100 }}
onBlur={handleBlur}
/>
<Button
margin="normal"
type="button"
color="secondary"
variant="outlined"
margin="dense"
style={{ margin: 8, width: 30 }}
className={classes.textField}
onClick={() => arrayHelpers.remove(index)}
> x
</Button>
<Button
margin="normal"
type="button"
variant="contained"
color="default"
className={classes.textField}
onClick={() => arrayHelpers.push({ name: '', amount: '', optional: false })}
>Add
</Button>
</div>
))}
</div>
)}
/>
</View>
<FieldArray
name="instructions"
render={arrayHelpers => (
<div>
{values.instructions.map((item, index) => (
<div key={index}>
<TextField
variant="outlined"
label="Instruction"
name={`instructions.${index}`}
value={item}
margin="normal"
className={classes.textField}
onChange={handleChange}
style={{ margin: 8, width: 350 }}
onBlur={handleBlur}
/>
<Button
margin="normal"
type="button"
color="secondary"
variant="outlined"
margin="dense"
style={{ margin: 8, width: 30 }}
className={classes.textField}
onClick={() => arrayHelpers.remove(index)}
> x
</Button>
</div>
))}
<Button
margin="normal"
type="button"
variant="contained"
color="default"
className={classes.textField}
onClick={() => arrayHelpers.push('')}
>Add
</Button>
</div>
)}
/>
<div>
<Button color="primary" variant="contained" className={classes.textField} fullWidth type="submit">
Submit
</Button>
</div>
</Form>
)}
</Formik>
You cannot use #material-ui/core for React Native projects.
#material-ui/core can work for expo because it's web based. But I'm pretty sure that it won't work for native environments.
I'd like to recommend alternatives, but I don't use material design for React Native because it simply doesn't fit to iOS.

Nivo Pie Chart Not Rendering

I'm using the nivo charting library and am struggling to get my pie charts to render. I really don't understand why the pie chart isn't showing up.
Here is my core component code for the dashboard:
import React, { useState, useEffect } from "react";
import Amplify, { Storage } from "aws-amplify";
import Paper from "#material-ui/core/Paper";
import Box from "#material-ui/core/Box";
import Grid from "#material-ui/core/Grid";
import awsmobile from "./aws-exports";
import * as d3 from "d3";
import CircularProgress from "#material-ui/core/CircularProgress";
import MyResponsivePie from "./pieConfig";
import useStyles from "./useStyles";
import AppBar from "#material-ui/core/AppBar";
import Toolbar from "#material-ui/core/Toolbar";
import IconButton from "#material-ui/core/IconButton";
import CloudDownloadIcon from "#material-ui/icons/CloudDownload";
import Typography from "#material-ui/core/Typography";
Amplify.configure(awsmobile);
Storage.configure({ level: "private" });
export default function Dashboard() {
useEffect(() => {
getFile();
}, []);
const classes = useStyles();
const [dashboard, showDashboard] = useState(false);
const [dashboardfile, setFile] = useState();
const getFile = async () => {
const url = await get_url().catch(err => getFile());
const file = await d3.csv(url);
if (file) {
console.log(file);
setFile(file);
showDashboard(true);
}
};
const get_url = () => {
var url = Storage.get("output.csv", { level: "private" }, { expires: 60 });
console.log(url);
return url;
};
const countColumnValues = (file, column) => {
var data_count = d3
.nest()
.key(function(d) {
return d[column];
})
.rollup(function(leaves) {
return leaves.length;
})
.entries(file);
console.log(data_count);
return data_count;
};
const generatePie = (file, column) => {
var data = countColumnValues(file, column);
return data;
};
return (
<Box className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton
edge="start"
className={classes.menuButton}
color="inherit"
>
<CloudDownloadIcon onClick={get_url}></CloudDownloadIcon>
</IconButton>
<Typography variant="h6" className={classes.title}>
Atreides Controls NLP Dashboard
</Typography>
</Toolbar>
</AppBar>
{dashboard === false && (
<div className={classes.circle}>
<CircularProgress />
</div>
)}
{dashboard && (
<div className={classes.root}>
<Grid container direction="row" space={3}>
<Grid item xs>
<Paper className={classes.paper}>
<div className={classes.pie}>
<MyResponsivePie
id="contains_who_pie"
data={generatePie(dashboardfile, "contains_whos")}
/>{" "}
</div>
</Paper>
</Grid>
<Grid item xs>
<Paper className={classes.paper}>
<div className={classes.pie}>
<MyResponsivePie
id="contains_what_pie"
data={generatePie(dashboardfile, "contains_whats")}
/>
</div>
</Paper>
</Grid>
<Grid item xs>
<Paper className={classes.paper}>
<div className={classes.pie}>
<MyResponsivePie
id="contains_how_pie"
data={generatePie(dashboardfile, "contains_hows")}
/>
</div>
</Paper>
</Grid>
</Grid>
<Grid container direction="row" space={3}>
<Grid item xs>
<Paper className={classes.paper}>
<div className={classes.pie}>
<MyResponsivePie
id="multiple_who_pie"
data={generatePie(dashboardfile, "multiple_whos")}
/>
</div>
</Paper>
</Grid>
<Grid item xs>
<Paper className={classes.paper}>
<div className={classes.pie}>
<MyResponsivePie
id="multiple_what_pie"
data={generatePie(dashboardfile, "multiple_whats")}
/>{" "}
</div>
</Paper>
</Grid>
<Grid item xs>
<Paper className={classes.paper}>
<div className={classes.pie}>
<MyResponsivePie
id="multiple_how_pie"
data={generatePie(dashboardfile, "multiple_hows")}
/>
</div>
</Paper>
</Grid>
</Grid>
<Grid container direction="row" space={3}>
<Grid item xs>
<Paper className={classes.paper}>
<div className={classes.pie}>
<MyResponsivePie
id="risk_relevance_pie"
data={generatePie(
dashboardfile,
"control_relevance_to_risk"
)}
/>
</div>
</Paper>
</Grid>
<Grid item xs>
<Paper className={classes.paper}>
<div className={classes.pie}>
<MyResponsivePie
id="automated_manual_pie"
data={generatePie(dashboardfile, "")}
/>
</div>
</Paper>
</Grid>
<Grid item xs>
<Paper className={classes.paper}>
<div className={classes.pie}>
<MyResponsivePie
id="preventative_detective_pie"
data={generatePie(dashboardfile, "")}
/>
</div>
</Paper>
</Grid>
</Grid>
</div>
)}
</Box>
);
}
The pie chart component is configured using this component that I am importing:
import React from "react";
import { ResponsivePie } from "#nivo/pie";
const MyResponsivePie = ({ data }) => (
<ResponsivePie
data={data}
margin={{ top: 40, right: 80, bottom: 80, left: 80 }}
startAngle={-180}
innerRadius={0.5}
padAngle={0.7}
cornerRadius={3}
colors={{ scheme: "nivo" }}
borderWidth={1}
borderColor={{ theme: "grid.line.stroke" }}
radialLabelsSkipAngle={10}
radialLabelsTextXOffset={6}
radialLabelsTextColor="#333333"
radialLabelsLinkOffset={0}
radialLabelsLinkDiagonalLength={16}
radialLabelsLinkHorizontalLength={24}
radialLabelsLinkStrokeWidth={3}
radialLabelsLinkColor={{ from: "color", modifiers: [] }}
slicesLabelsSkipAngle={10}
slicesLabelsTextColor="#333333"
animate={true}
motionStiffness={90}
motionDamping={15}
legends={[
{
anchor: "bottom",
direction: "row",
translateY: 56,
itemWidth: 100,
itemHeight: 18,
itemTextColor: "#999",
symbolSize: 18,
symbolShape: "circle",
effects: [
{
on: "hover",
style: {
itemTextColor: "#000"
}
}
]
}
]}
/>
);
export default MyResponsivePie;
and my styles file looks like this
import { green } from "#material-ui/core/colors";
import { makeStyles } from "#material-ui/core/styles";
import { forceCenter } from "d3";
const useStyles = makeStyles(theme => ({
root: {
height: "100vh"
},
success: {
backgroundColor: green[600]
},
error: {
backgroundColor: theme.palette.error.dark
},
icon: {
fontSize: 20
},
iconVariant: {
opacity: 0.9,
marginRight: theme.spacing(1)
},
message: {
display: "flex",
alignItems: "center"
},
image: {
backgroundImage: "url(https://source.unsplash.com/8WFnEehJWso)",
backgroundRepeat: "no-repeat",
backgroundColor:
theme.palette.type === "dark"
? theme.palette.grey[900]
: theme.palette.grey[50],
backgroundSize: "cover",
backgroundPosition: "center"
},
paper: {
margin: theme.spacing(1.5, 3),
display: "flex",
flexDirection: "column",
alignItems: "center"
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(1)
},
submit: {
margin: theme.spacing(3, 0, 2)
},
card: {
maxWidth: 600
},
media: {
height: 500
},
circle: {
display: "flex",
"& > * + *": {
marginLeft: theme.spacing(2)
}
},
menuButton: {
marginRight: theme.spacing(2)
},
title: {
flexGrow: 1,
alignContent: "center"
},
pie: {
height: 250
}
}));
export default useStyles;
Lastly an example of my data that is coming back from the generate pie function is like this:
[
{key: "True", value: 7981},
{key: "False", value: 950}
]
The issue I had was rather daft, the container object did not have a specified size.

Categories