Below is the functional signup component in React. I have one particular problem with the DatePicker component. It renders correctly on the sign up form. When I click on the submit button, it does not give me the selected date but instead it sends me the initial state of the component. Other states such as fullname, password and email are updated accordingly.
To prove that the date was not updated, I tried putting "null" in the useState() and when I get the result in the database, as expected the date is of a "null" type. How do I update the initial state to the updated state?
import React, { useState, useContext, Fragment } from "react";
import Avatar from "#material-ui/core/Avatar";
import Button from "#material-ui/core/Button";
import CssBaseline from "#material-ui/core/CssBaseline";
import TextField from "#material-ui/core/TextField";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import Checkbox from "#material-ui/core/Checkbox";
import Link from "#material-ui/core/Link";
import Grid from "#material-ui/core/Grid";
import Box from "#material-ui/core/Box";
import LockOutlinedIcon from "#material-ui/icons/LockOutlined";
import Typography from "#material-ui/core/Typography";
import { makeStyles } from "#material-ui/core/styles";
import Container from "#material-ui/core/Container";
import { signup } from "./auth-api";
import DatePicker from "./DatePicker";
import Copyright from "./Copyright";
import AuthApi from "../utils/AuthApi";
import { MuiPickersUtilsProvider } from "#material-ui/pickers"; //Date picker util provider
import DateFnsUtils from "#date-io/date-fns"; // Date util library
// We can use inline-style
const style = {
background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
borderRadius: 3,
border: 0,
color: "white",
height: 48,
padding: "0 30px",
boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
};
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center",
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(3),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));
export default function SignUp() {
const classes = useStyles();
const joindate = new Date();
const [fullname, setFullname] = useState();
const [email, setEmail] = useState();
const [password, setPassword] = useState();
const [dateofbirth, setSelectedDate] = useState(new Date());
const handleOnChange = (e) => {
if (e.target.name === "fullname") {
setFullname(e.target.value);
} else if (e.target.name === "username") {
setEmail(e.target.value);
} else if (e.target.name === "password") {
setPassword(e.target.value);
}
};
const handleDateChange = (date) => {
setSelectedDate(date);
};
const authApi = React.useContext(AuthApi);
const handleSignUp = async (e) => {
e.preventDefault();
const res = await signup({
joindate,
fullname,
email,
password,
dateofbirth,
});
if (res.data.auth) {
authApi.setAuth(true);
}
//console.log(res);
};
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign up
</Typography>
<form className={classes.form} noValidate>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
autoComplete="fname"
name="fullname"
variant="outlined"
required
fullWidth
id="fullName"
label="Full Name"
autoFocus
onChange={handleOnChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="email"
label="Email Address"
name="username"
autoComplete="email"
onChange={handleOnChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
onChange={handleOnChange}
/>
</Grid>
<Grid item xs={12}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Fragment>
<DatePicker
inputVariant="outlined"
required
fullWidth
id="dob"
name="dob"
disableFuture
openTo="year"
format="dd-MM-yyyy"
label="Date of Birth"
views={["year", "month", "date"]}
value={dateofbirth}
onChange={handleDateChange}
/>
</Fragment>
</MuiPickersUtilsProvider>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
style={style}
className={classes.submit}
onClick={handleSignUp}
>
Sign Up
</Button>
<Grid container justify="flex-end">
<Grid item>
<Link href="/signin" variant="body2">
Already have an account? Sign in
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={5}>
<Copyright />
</Box>
</Container>
);
}
Related
I'm trying to use text field from material ui and I use Box element and i got an error message saying that there is an error in box.js. Box.js is a built in file from material and i can't change it. Here's my component codes. I don't understand why the error is in box.js. How can i fix it?
import * as React from 'react';
import Box from '#mui/material/Box';
import Button from '#mui/material/Button';
import styled from "styled-components";
import Layout from '../../Layouts/SideMenu';
import Stack from '#mui/material/Stack';
import TextField from '#mui/material/TextField';
import '#fontsource/roboto/300.css';
import '#fontsource/roboto/400.css';
import '#fontsource/roboto/500.css';
import '#fontsource/roboto/700.css';
const Wrapper = styled.section`
padding: 4em;
`;
export default function Create() {
const [age, setAge] = React.useState('');
return (
<Layout>
<Wrapper>
<form action="">
<Stack spacing={3} direction="column">
<h2>Form Tambah Siswa</h2>
<TextField id="outlined-basic" label="Nama" variant="outlined" />
<Box
component="form"
sx={{
'& > :not(style)': { m: 1, width: '25ch' },
}}
noValidate
autoComplete="off"
>
<TextField id="outlined-basic" label="Email" variant="outlined" />
</Box>
<Box
component="form"
sx={{
'& > :not(style)': { m: 1, width: '25ch' },
}}
noValidate
autoComplete="off"
>
<TextField id="outlined-basic" label="Password" variant="outlined" />
</Box>
<Box
component="form"
sx={{
'& > :not(style)': { m: 1, width: '25ch' },
}}
noValidate
autoComplete="off"
>
<TextField id="outlined-basic" label="Confirm Password" variant="outlined" />
</Box>
<Button variant="contained" type='submit'>Submit</Button>
</Stack>
</form>
</Wrapper>
</Layout>
)
}
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;
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>
I am new to React.js and material-ui. I am trying to make a simple sign up form, but I got an error. I have tested my backend on insomnia and all its routes work, so I believe my error is on my front. My sign up script is this one below. By the way, my error only says that it is a create error. Can you guys help me?
import React from 'react';
import { style } from './styles';
import Button from '#material-ui/core/Button';
import CssBaseline from '#material-ui/core/CssBaseline';
import TextField from '#material-ui/core/TextField';
import Link from '#material-ui/core/Link';
import Grid from '#material-ui/core/Grid';
import Typography from '#material-ui/core/Typography';
import Container from '#material-ui/core/Container';
import { useState } from "react";
import api from "../../services/api"
function Cadastro() {
const classes = style();
const [nome, setNome] = useState("");
const [email, setEmail] = useState("");
const [cpf, setCpf] = useState("");
const [senha, setSenha] = useState("");
const [rg, setRg] = useState("");
const [data_nascimento, setDataNascimento] = useState("");
async function save(){
try{
await api.post('/cadastro', {
nome,
cpf,
email,
rg,
data_nascimento,
senha
})
}catch(err){
console.log(err)
}
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Typography component="h1" variant="h5">
Cadastro
</Typography>
<form className={classes.form} noValidate>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<TextField
// value={nome}
required
fullWidth
id="nome"
label="Nome"
onChange={e => setNome(e.target.value)}
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
required
fullWidth
id="cpf"
label="CPF"
// value={cpf}
onChange={e => setCpf(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
id="email"
label="Email"
// value={email}
onChange={e => setEmail(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
// value={senha}
label="Senha"
type="password"
id="senha"
onChange={e => setSenha(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
// value={rg}
label="RG"
id="rg"
onChange={e => setRg(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
// value={data_nascimento}
type="date"
id="data_nascimento"
onChange={e => setDataNascimento(e.target.value)}
/>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={save}
>
Cadastrar
</Button>
</form>
</div>
</Container>
);
}
export default Cadastro;
EDIT 1:
My error:
Error: "Request aborted"
createError createError.js:16
handleAbort xhr.js:73
index.js:36
The development server has disconnected.
Refresh the page if necessary. webpackHotDevClient.js:76
[HMR] Waiting for update signal from WDS... log.js:24
The index file is the code above.
Now, my api script is below:
import axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:5000'
});
export default api;
I'm completely new in MaterialUI. I'm working on my first project right now and trying to make use of templates form its page. I've loaded two .tsx files with log in view and main dashboard view. I'd like to show main dashboard view after clicking Login button on log in view. Both files have its own export default function FnName() function with const classes = useStyles(); and it seems to cause my problems. The way of using hooks is the issue here I guess. But how to pass this function to onClick handler event button? You can see my project here:
https://codesandbox.io/s/adoring-leftpad-6nwv2?file=/src/SignIn.tsx
Somebody can help?
Please check this example:
App Component
import React, {useEffect, useState} from 'react';
import SignIn from "./material-ui/signin-template/SignIn";
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";
import { createBrowserHistory as history} from 'history';
import MiniDrawer from "./material-ui/signin-template/Dashboard";
class App extends React.Component {
render() {
return (
<div>
<Router history={history}>
<Switch>
<Route path="/" exact component={SignIn}/>
<Route path="/dashboard" component={MiniDrawer}/>
</Switch>
</Router>
</div>
)
}
}
export default App;
SingIn Component
import React from "react";
import Avatar from "#material-ui/core/Avatar";
import Button from "#material-ui/core/Button";
import CssBaseline from "#material-ui/core/CssBaseline";
import TextField from "#material-ui/core/TextField";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import Checkbox from "#material-ui/core/Checkbox";
import Link from "#material-ui/core/Link";
import Grid from "#material-ui/core/Grid";
import Box from "#material-ui/core/Box";
import LockOutlinedIcon from "#material-ui/icons/LockOutlined";
import Typography from "#material-ui/core/Typography";
import {makeStyles} from "#material-ui/core/styles";
import Container from "#material-ui/core/Container";
import {Redirect, useHistory} from "react-router-dom";
function Copyright() {
return (
<Typography variant="body2" color="textSecondary" align="center">
{"Copyright © "}
<Link color="inherit" href="https://material-ui.com/">
Your Website
</Link>{" "}
{new Date().getFullYear()}
{"."}
</Typography>
);
}
const useStyles = makeStyles(theme => ({
paper: {
marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center"
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(1)
},
submit: {
margin: theme.spacing(3, 0, 2)
}
}));
export default function SignIn() {
const classes = useStyles();
let history = useHistory();
return (
<Container component="main" maxWidth="xs">
<CssBaseline/>
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon/>
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
/>
<TextField
variant="outlined"
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
onClick={()=>{
history.push('/dashboard')
}}
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
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>
</form>
</div>
<Box mt={8}>
<Copyright/>
</Box>
</Container>
);
}
Dashboard Component
import React from "react";
import clsx from "clsx";
import {
createStyles,
makeStyles,
useTheme,
Theme
} from "#material-ui/core/styles";
import Button from "#material-ui/core/Button";
import Drawer from "#material-ui/core/Drawer";
import AppBar from "#material-ui/core/AppBar";
import Toolbar from "#material-ui/core/Toolbar";
import List from "#material-ui/core/List";
import CssBaseline from "#material-ui/core/CssBaseline";
import Typography from "#material-ui/core/Typography";
import Divider from "#material-ui/core/Divider";
import IconButton from "#material-ui/core/IconButton";
import MenuIcon from "#material-ui/icons/Menu";
import ChevronLeftIcon from "#material-ui/icons/ChevronLeft";
import ChevronRightIcon from "#material-ui/icons/ChevronRight";
import ListItem from "#material-ui/core/ListItem";
import ListItemIcon from "#material-ui/core/ListItemIcon";
import ListItemText from "#material-ui/core/ListItemText";
import InboxIcon from "#material-ui/icons/MoveToInbox";
import MailIcon from "#material-ui/icons/Mail";
import MapOutlinedIcon from "#material-ui/icons/MapOutlined";
import DriveEtaOutlinedIcon from "#material-ui/icons/DriveEtaOutlined";
import PeopleAltOutlinedIcon from "#material-ui/icons/PeopleAltOutlined";
import DirectionsOutlinedIcon from "#material-ui/icons/DirectionsOutlined";
import AssessmentOutlinedIcon from "#material-ui/icons/AssessmentOutlined";
import ReportProblemOutlinedIcon from "#material-ui/icons/ReportProblemOutlined";
import AccountCircleOutlinedIcon from "#material-ui/icons/AccountCircleOutlined";
import { Redirect, useHistory } from "react-router-dom";
import ExitToAppIcon from "#material-ui/icons/ExitToApp";
const drawerWidth = 240;
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
display: "flex"
},
appBar: {
zIndex: theme.zIndex.drawer + 1,
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
})
},
appBarShift: {
marginLeft: drawerWidth,
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen
})
},
menuButton: {
marginRight: 36
},
hide: {
display: "none"
},
drawer: {
width: drawerWidth,
flexShrink: 0,
whiteSpace: "nowrap"
},
drawerOpen: {
width: drawerWidth,
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen
})
},
drawerClose: {
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
}),
overflowX: "hidden",
width: theme.spacing(7) + 1,
[theme.breakpoints.up("sm")]: {
width: theme.spacing(9) + 1
}
},
toolbar: {
display: "flex",
alignItems: "center",
justifyContent: "flex-end",
padding: theme.spacing(0, 1),
// necessary for content to be below app bar
...theme.mixins.toolbar
},
content: {
flexGrow: 1,
padding: theme.spacing(3)
}
})
);
function MiniDrawer() {
const classes = useStyles();
let history = useHistory();
const theme = useTheme();
const [open, setOpen] = React.useState(false);
const handleDrawerOpen = () => {
setOpen(true);
};
const handleDrawerClose = () => {
setOpen(false);
};
return (
<div className={classes.root}>
<CssBaseline />
<AppBar
position="fixed"
className={clsx(classes.appBar, {
[classes.appBarShift]: open
})}
>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={handleDrawerOpen}
edge="start"
className={clsx(classes.menuButton, {
[classes.hide]: open
})}
>
<MenuIcon />
</IconButton>
</Toolbar>
</AppBar>
<Drawer
variant="permanent"
className={clsx(classes.drawer, {
[classes.drawerOpen]: open,
[classes.drawerClose]: !open
})}
classes={{
paper: clsx({
[classes.drawerOpen]: open,
[classes.drawerClose]: !open
})
}}
>
<div className={classes.toolbar}>
<IconButton onClick={handleDrawerClose}>
{theme.direction === "rtl" ? (
<ChevronRightIcon />
) : (
<ChevronLeftIcon />
)}
</IconButton>
</div>
<div className={classes.toolbar} />
<div className={classes.toolbar} />
<div className={classes.toolbar} />
<IconButton
onClick={() => {
history.push("/");
}}
>
<ExitToAppIcon />
</IconButton>
<Divider />
<List>
{["Mapa", "Pojazdy", "Kierowcy", "Trasy", "Raporty", "Alerty"].map(
(text, index) => (
<ListItem
button
key={text}
onClick={event => {
console.log(event.currentTarget);
history.push("/");
}}
>
<ListItemIcon>
{index === 0 && <MapOutlinedIcon />}
{index === 1 && <DriveEtaOutlinedIcon />}
{index === 2 && <PeopleAltOutlinedIcon />}
{index === 3 && <DirectionsOutlinedIcon />}
{index === 4 && <AssessmentOutlinedIcon />}
{index === 5 && <ReportProblemOutlinedIcon />}
</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
)
)}
</List>
</Drawer>
<main className={classes.content}>
<div className={classes.toolbar} />
<Typography paragraph />
</main>
</div>
);
}
export default MiniDrawer;
Here is the Code Sandbox