Material UI: Grid does not put select in row - javascript

I'm new in full stack developing and I'm trying to code something to understand better frontend with React JS and Material UI. I've write a page that shows posts in backend but I want to Select Items all in a row, on Material UI website I've read that I've to write like this in order to show elements in a row:
Marketplace.js
import { Grid } from '#material-ui/core'
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import regioni from '../utils/where'
import Adv from '../components/marketplace/Adv';
import NewAdv from '../components/marketplace/NewAdv';
import Profile from '../components/profile/Profile';
import PostSkeleton from '../utils/PostSkeleton';
import Select from '#material-ui/core/Select';
import Input from '#material-ui/core/Input';
import InputLabel from '#material-ui/core/InputLabel';
import MenuItem from '#material-ui/core/MenuItem';
import TextField from '#material-ui/core/TextField';
import Radio from '#material-ui/core/Radio';
import RadioGroup from '#material-ui/core/RadioGroup';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import Button from '#material-ui/core/Button';
import FormLabel from '#material-ui/core/FormLabel';
import { connect } from 'react-redux';
class marketplace extends Component {
state = {
query:'',
errors:{},
type:'Vendo',
title:'',
product:'Singole',
body:'',
regione:'Abruzzo',
provincia:'',
};
componentDidMount(){
const {
user:{
authenticated, credentials:{
handle,
ygo,
mtg,
kf
}
}} = this.props;
render() {
return (
<Grid container>
<Grid item sm={4} xs={12}>
<Profile/>
</Grid>
<Grid item sm={8} xs={12}>
<TextField
name="search"
floatingLabelText="Cerca"
value={this.state.query}
onChange={this.searchChange}
/>
<Button type="submit" variant="contained" color="primary" onClick={this.handleSearch}>
Cerca
</Button>
<Grid item xs={6} sm={3} >
<FormLabel component="legend">Tipo</FormLabel>
<RadioGroup aria-label="Tipo" name="type" color="primary" value={this.state.type} onChange={this.radioTypeChange}>
<FormControlLabel value="Vendo" control={<Radio />} label="Vendo" />
<FormControlLabel value="Scambio" control={<Radio />} label="Scambio" />
<FormControlLabel value="Cerco" control={<Radio />} label="Cerco" />
</RadioGroup>
</Grid>
<Grid item xs={6} sm={3}>
<FormLabel component="legend">Prodotto</FormLabel>
<RadioGroup aria-label="Prodotto" name="product" color="primary" value={this.state.product} onChange={this.radioProductChange}>
<FormControlLabel value="Singole" control={<Radio />} label="Singole" />
<FormControlLabel value="Lista" control={<Radio />} label="Lista" />
<FormControlLabel value="Sigillato" control={<Radio />} label="Sigillato" />
<FormControlLabel value="Accessori" control={<Radio />} label="Accessori" />
</RadioGroup>
</Grid>
<Grid item xs={6} sm={3}>
<InputLabel id="regioni">Regione</InputLabel>
<Select
labelId="Regione"
id="regioni"
value={this.state.regione}
onChange={this.regionChange}
input={<Input />}
MenuProps={MenuProps}
>
{regioni.map((regione) => (
<MenuItem value={regione.regioneName}>
{regione.regioneName}
</MenuItem>
))}
</Select>
</Grid>
<Grid item xs={6} sm={3}>
<InputLabel id="demo-simple-select-label">Provincia</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={this.state.provincia}
onChange={this.whereChange}
disabled={!this.state.regione}
>
{this.state.regione
? regioni
.find(({ regioneName }) => regioneName === this.state.regione)
.province.map((prov) => (
<MenuItem value={prov.name}>
{prov.name}
</MenuItem>
))
: []}
</Select>
</Grid>
<Button type="submit" variant="contained" color="primary" onClick={this.handleFilter}>
filter
</Button>
<Button type="submit" variant="contained" color="primary" onClick={this.handleReset}>
Reset
</Button>
<NewAdv game={game}/>
{recentAdvsMarkup}
</Grid>
<Grid item sm={4} xs={12}>
</Grid>
</Grid>
)
}
}
marketplace.propTypes={
data: PropTypes.object.isRequired,
user: PropTypes.object.isRequired
}
const mapStateToProps = state =>({
data: state.data,
user: state.user,
game: state.UI
})
export default connect(mapStateToProps,)(marketplace)
But they were showed in a columb. How can I do?

You can wrap elements in a Box Material UI component.
<Box display="flex" flexDirection="row">
<Box>
// Element
</Box>
<Box>
// Element
</Box>
</Box>

Related

Link tag changes my history location but then changes back to original home page React.js

So I have been having this issue with a project I've been working on for 2 days now and I don't know why. I have used React-router-dom before for my webapps and I have never encountered this issue in all the months I've used React.js I basically have my Switch component, BrowserRouter wrapped around App.js, and everything, but every time I click the link to my new route "/register", the URL would change for a few 2 seconds and then change back to my login homepage. this happens without me doing anything or clicking anything. I've tried changing link tag attribute from to="/register" to href="/register" but that didn't work. It's infuriating, Here's my code:
Index.js
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter} from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
App.js
import React,{Component} from 'react';
import { Router, Switch, Route, withRouter, Link} from 'react-router-dom'
import HomePage from "./components/HomePage";
import Register from "./components/Register"
import Dashboard from "./components/Dashboard"
// import Link from '#material-ui/core/Link';
// import { background } from "./images/7f76e8e7692375107e5998013155af0d.jpg";
// import { TravelerEffect, MosaicGroundEffect, OceanEffect,
// RainEffect, SeaWaveEffect, SnowFallEffect, SnowFallSlowEffect,
// SpacingEffect, CloudWaveEffect
// } from 'react-background-animation'
class App extends Component {
state = {
user: {
email: "",
username: "",
is_active: "",
first_name: "",
last_name: "",
bio: "",
age: "",
birth_place: "",
school: "",
occupation: "",
what_are_you_seeking_on_site: "",
profile_pic: null,
loginErrors: "",
},
token: "",
}
handleResponse (resp) {
console.log(resp.user);
if (resp.user) {
localStorage.setItem('token', resp.token)
this.setState({
user: resp.user,
token: resp.token
}, () => {
this.props.history.push("/dashboard")
})
}
else {
alert(resp.error)
}
}
componentDidMount(){
if (localStorage.getItem("token")) {
fetch('http://localhost:8000/current_user/', {
headers: {
Authorization: `Bearer ${localStorage.token}`
}
})
.then(r => r.json())
.then(this.handleResp)
}
}
handleRegister(newUser){
fetch( "http://127.0.0.1:8000/rest-auth/registration/", {
method: "POST",
headers: {
'content-type': "application/json"
},
body: JSON.stringify(newUser)
})
.then(res => res.json())
.then(this.handleResponse)
}
handleLogin(returningUser){
fetch('http://127.0.0.1:8000/rest-auth/login/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(returningUser)
})
.then(res => res.json())
.then(this.handleResponse)
}
renderRegisterForm = (routerProps) => {
if (routerProps.location.pathname === "/register") {
// debugger
return <Register formName="Register Form"
handleSubmit={this.handleRegister}
/>
}else if(routerProps.location.pathname === "/") {
return <HomePage formName="Log into Account"
handleSubmit={this.handleLogin}
/>
}
}
render() {
return (
<div>
{/* <Link to="/register">Sign Up</Link> */}
<Switch>
<Route exact path="/" render={this.renderRegisterForm} />
<Route exact path="/register" render={this.renderRegisterForm} />
<Route path="/dashboard" exact component={Dashboard} />
<Route render={ () => <p>Page not Found</p> } />
</Switch>
{/* <Link href="/register"
// onClick={this.handleRegisterLinkPage}
variant="body1">
{"Don't have an account? Sign Up"}
</Link> */}
</div>
);
}
}
export default withRouter(App);
my HomePage.jsx (which is basically my login page)
import React from 'react';
import {Redirect} from "react-router-dom"
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 Paper from '#material-ui/core/Paper';
import Box from '#material-ui/core/Box';
import Grid from '#material-ui/core/Grid';
// import LockOutlinedIcon from '#material-ui/icons/LockOutlined';
import Typography from '#material-ui/core/Typography';
import { withStyles } from '#material-ui/core/styles';
const useStyles = theme => ({
root: {
height: '100vh',
},
image: {
backgroundImage: 'url(https://source.unsplash.com/random)',
backgroundRepeat: 'no-repeat',
backgroundColor:
theme.palette.type === 'light' ? theme.palette.grey[50] : theme.palette.grey[900],
backgroundSize: 'cover',
backgroundPosition: 'center',
},
paper: {
margin: theme.spacing(8, 4),
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),
},
});
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>
);
}
class HomePage extends React.Component {
// handleRegisterLinkPage = (event) => {
// event.preventDefault()
// return<Redirect to={"/register"}/>
// // debugger
// }
render(){
const {classes} = this.props
return (
<Grid container component="main" className={classes.root}>
<CssBaseline />
<Grid item xs={false} sm={4} md={7} className={classes.image} />
<Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
<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
type="submit"
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="/register"
// onClick={this.handleRegisterLinkPage}
variant="body1">
<Button> Don't have an account? Sign Up</Button>
</Link>{' '}
</Grid>
</Grid>
<Box mt={5}>
<Copyright />
</Box>
</form>
</div>
</Grid>
</Grid>
);
}
}
export default withStyles(useStyles)(HomePage)
And Lastly My register page, which I feel I shouldn't have to show, but here it is anyway
import React, { useState, useEffect } 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 TextareaAutosize from '#material-ui/core/TextareaAutosize';
import { MuiPickersUtilsProvider, KeyboardDatePicker } from '#material-ui/pickers';
import FormControl from '#material-ui/core/FormControl';
import FormLabel from '#material-ui/core/FormLabel';
import Radio from '#material-ui/core/Radio';
import RadioGroup from '#material-ui/core/RadioGroup';
import DateFnsUtils from '#date-io/date-fns';
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(3),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));
export default function Register() {
const classes = useStyles();
const [email, setEmail] = useState(" ")
const [password, setPassword] = useState(" ")
const [confirmPassword, setConfirmPassword] = useState(" ")
const [username, setUsername] = useState(" ")
const [birthPlace, setBirthPlace] = useState(" ")
const [bio, setBio] = useState(" ")
const [school, setSchool] = useState(" ")
const [firstName, setFirstName] = useState(" ")
const [lastName, setLastName] = useState(" ")
const [occupation, setOccupation] = useState(" ")
const [what_are_you_seeking_on_site, setWhat_are_you_seeking_on_site] = useState("Friendship")
const [age, setAge] = useState(new Date('2014-08-18T21:11:54'));
const [errors, setErrors] = useState(" ")
// const [selectedDate, setSelectedDate] =
// const [value, setValue] = React.useState('Friendship');
useEffect(() => {
if (localStorage.getItem('token') !== null) {
window.location.replace('http://localhost:3000/dashboard');
} else {
window.location.replace('http://localhost:3000/')
}
}, []);
const handleSubmit = e => {
e.preventDefault();
const user = {
email: email,
username: username,
birthPlace: birthPlace,
bio: bio,
school: school,
age: age,
password: password,
confirmPassword: confirmPassword,
firstName: firstName,
lastName: lastName,
occupation: occupation,
what_are_you_seeking_on_site: what_are_you_seeking_on_site,
};
fetch('http://127.0.0.1:8000/rest-auth/registration/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(res => res.json())
.then(data => {
if (data.key) {
localStorage.clear();
localStorage.setItem('token', data.key);
window.location.replace('http://localhost:3000/dashboard');
} else {
setEmail('');
setPassword('');
setConfirmPassword('');
localStorage.clear();
setErrors(true);
}
});
};
const handleChange = (event) => {
setWhat_are_you_seeking_on_site(event.target.value);
};
const handleDateChange = (date) => {
setAge(date);
};
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} onSubmit={handleSubmit} noValidate>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<Grid item xs={12} sm={6}>
<TextField
autoComplete="username"
name="Username"
variant="outlined"
required
fullWidth
id="Username"
label="Username"
autoFocus
value={e => setUsername(e.target.value)}
/>
</Grid>
<TextField
autoComplete="fname"
name="firstName"
variant="outlined"
required
fullWidth
id="firstName"
label="First Name"
autoFocus
value={e => setFirstName(e.target.value)}
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
variant="outlined"
required
fullWidth
id="lastName"
label="Last Name"
name="lastName"
value={e => setLastName(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="email"
label="Email Address"
name="email"
value={e => setEmail(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
value={e => setPassword(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="Confirm password"
label="Confirm Password"
type="password2"
id="password2"
value={e => setConfirmPassword(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextareaAutosize
aria-label="minimum height"
fullWidth
label="Bio"
rowsMin={3}
placeholder="Minimum 3 rows"
value={e => setBio(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="Birth Place"
label="Where were you born"
id="birthPlace"
value={e => setBirthPlace(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="School"
label="School"
id="School"
value={e => setSchool(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="Occupation"
label="Occupation"
id="Occupation"
value={e => setOccupation(e.target.value)}
/>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset">
<FormLabel component="legend">What are you here for</FormLabel>
<RadioGroup aria-label="what_are_you_seeking_on_site" name="what_are_you_seeking_on_site" value={what_are_you_seeking_on_site} onChange={handleChange}>
<FormControlLabel value="Dating" control={<Radio />} label="Dating" />
<FormControlLabel value="Friendship" control={<Radio />} label="Friendship" />
<FormControlLabel value="Networking" control={<Radio />} label="Networking" />
<FormControlLabel value="Business" control={<Radio />} label="Business" />
</RadioGroup>
</FormControl>
</Grid>
<Grid item xs={12}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
margin="normal"
id="date-picker-dialog"
label="Date picker dialog"
format="MM/dd/yyyy"
// value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change date',
}}
value={e => setAge(e.target.value)}
/>
</MuiPickersUtilsProvider>
</Grid>
<Grid item xs={12}>
<FormControlLabel
control={<Checkbox value="allowExtraEmails" color="primary" />}
label="I want to receive inspiration, marketing promotions and updates via email."
/>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign Up
</Button>
<Grid container justify="flex-end">
<Grid item>
<Link href="/" variant="body2">
Already have an account? Sign in
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={5}>
<Copyright />
</Box>
</Container>
);
}
Please Help me
When your Register component mounts you've an useEffect hook that runs and either bounces the user to "/dashboard" or "/".
useEffect(() => {
if (localStorage.getItem('token') !== null) {
window.location.replace('http://localhost:3000/dashboard');
} else {
window.location.replace('http://localhost:3000/')
}
}, []);
If the token exists and isn't null then bouncing a user to the dashboard path is probably acceptable. You may not want to bounce users to the homepage when they are trying to register so you can likely remove the else branch entirely.
useEffect(() => {
if (localStorage.getItem('token') !== null) {
window.location.replace('http://localhost:3000/dashboard');
}
}, []);

RadioButton checked field is not working for [No] by default .I had implemented it to set default as No and disable it

RadioButton checked field is not working for [No] by default .I had implemented it to set default as No and disable it and for Yes to update the fields
By default its coming unchecked for the both fields if i refresh the page.
I need to make it default for "NO"
Tried to fix the issue in various methods and ways but it's not fixing. I am not able to know why it's getting an error I don't understand the exact issue in the code. Could anyone help with the solution?
if i click Yes the user fields should be editable
code:
import React from "react";
import {
Box,
Typography,
Grid,
Link,
FormLabel,
RadioGroup,
Radio,
FormControlLabel,
} from "#material-ui/core";
import { makeStyles } from "#material-ui/core/styles";
import { TextField, CurrencyTxtField } from "components/core";
const useStyles = makeStyles(() => ({
dinline: {
display: "inline",
},
fieldproductTester: {
fontWeight: 700,
},
}));
const ProductTester = ({
errors,
values,
handleChange,
handleBlur,
refProp,
}) => {
const classes = useStyles();
return (
<div ref={refProp}>
<FormLabel color="secondary" component="legend" mb={2}>
<Typography variant="h4" component="h4">
Testers
</Typography>
</FormLabel>
<Box pt={2}>
<Grid container spacing={1}>
<Grid item xs={12}>
<Typography component="div" color="textPrimary">
Would you like to give your customers the option to purchase a
tester of this product?if so,please include information about the
tester in the product description.
</Typography>
</Grid>
<Grid item xs={8}>
<RadioGroup
className={classes.dinline}
aria-label="tester"
name="tester"
value={values.tester}
onChange={handleChange}
disabled={!values.tester}
>
<FormControlLabel value="Yes" control={<Radio />} label="Yes"/>
<FormControlLabel
value="No"
control={<Radio />}
label="No"
enabled={values.tester === "No"}
/>
</RadioGroup>
</Grid>
{values.tester && (
<>
<Grid item xs={12}>
<Typography
variant="inherit"
className={classes.fieldproductTester}
>
Tester Price
</Typography>
</Grid>
<Grid item xs={8}>
<CurrencyTxtField
id="testerPrice"
name="testerPrice"
label=" "
variant="outlined"
value={values.testerPrice}
currencySymbol="$"
outputFormat="number"
digitGroupSeparator=""
textAlign="left"
onChange={handleChange}
onBlur={handleBlur}
error={!!errors.testerPrice}
helperText={errors.testerPrice ? errors.testerPrice : ""}
disabled={values.tester === "No"}
/>
</Grid>
<Grid item xs={12}>
<Typography
variant="inherit"
className={classes.fieldproductTester}
>
Tester SKU
</Typography>
</Grid>
<Grid item xs={8}>
<TextField
id="productSku"
name="sku"
label=""
ariaLabel="SKU"
value={values.sku}
disabled={values.tester === "No"}
/>
</Grid>
</>
)}
</Grid>
</Box>
</div>
);
};
export default ProductTester;
I've tested the following configuration - it works as expected. "No" is selected as a default value. Try to use this code as a reference point and then add all additional functionality step by step to see when it stops working.
<RadioGroup
aria-label="tester"
name="tester"
defaultValue="No">
<FormControlLabel
value="Yes"
control={<Radio />}
label="Yes"/>
<FormControlLabel
value="No"
control={<Radio />}
label="No"/>
</RadioGroup>

React / MUI : How to call other class with hook to button in main App.js

I'm new to React/MUI.. I'm creating different components for now for a website, so the UI for now doesn't matter.
I'm facing this problem while trying to do a button to link me to the Sign Up page (Doing the same for Sign In):
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: ...
The following is my code:
SignUp.js
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';
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();
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} sm={6}>
<TextField
autoComplete="fname"
name="firstName"
variant="outlined"
required
fullWidth
id="firstName"
label="First Name"
autoFocus
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
variant="outlined"
required
fullWidth
id="lastName"
label="Last Name"
name="lastName"
autoComplete="lname"
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
</Grid>
<Grid item xs={12}>
<FormControlLabel
control={<Checkbox value="allowExtraEmails" color="primary" />}
label="I want to receive inspiration, marketing promotions and updates via email."
/>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign Up
</Button>
<Grid container justify="flex-end">
<Grid item>
<Link href="#" variant="body2">
Already have an account? Sign in
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={5}>
<Copyright />
</Box>
</Container>
);
}
App.js
import React from 'react';
import Container from '#material-ui/core/Container';
import Typography from '#material-ui/core/Typography';
import SignUp from './sign-up/SignUp.js';
import SignIn from './sign-in/SignIn.js';
import Box from '#material-ui/core/Box';
import Link from '#material-ui/core/Link';
import { Button, Paper } from '#material-ui/core';
export default function App() {
return (
<div>
<Container maxWidth="sm">
<Box my={4}>
<Typography variant="h4" component="h1" gutterBottom>
Creating a website!
</Typography>
<ProTip />
<button onClick={SignUp}>
Click me!
</button>
<SignIn />
<Copyright />
</Box>
</Container>
</div>
);
}
How do I properly convert in this case?
You're trying to call a React component as an event handler:
<button onClick={SignUp}>
That will not work. Instead you can for example create a flag, set it to true in the onClick handler and then render SignUp based on this flag.
const [showSignUp, setShowSignUp]= React.useState(false)
...
<button onClick={()=>setShowSignUp(s=>!s)}>Click me!</button>
{showSignUp ? <SignUp /> : <SignIn />}

How do I disable Accordion propagation after it has been clicked for the first time?

I have an Accordion with a TextField in the AccordionSummary (Material-UI) which when clicked opens the AccordionDetails with the rest of the form however, I can't work out how to stop multiple clicks on the field from triggering propagation to open and close the accordion contents after the first click. I don't want the newly visible form contents to disappear after the first click in AccountSummary. I know how to disable propagation when the field is entered for the first time but not how to allow propagation only once?
import React from "react";
import { Formik, Field, Form } from "formik";
import { TextField, Select } from "formik-material-ui";
import Grid from "#material-ui/core/Grid";
import Box from "#material-ui/core/Box";
import FormControl from "#material-ui/core/FormControl";
import MenuItem from "#material-ui/core/MenuItem";
import Button from "#material-ui/core/Button";
import Accordion from "#material-ui/core/Accordion";
import MuiAccordionDetails from "#material-ui/core/AccordionDetails";
import MuiAccordionSummary from "#material-ui/core/AccordionSummary";
import { withStyles } from "#material-ui/core/styles";
const AccordionSummary = withStyles({
root: {
"&.Mui-focused": {
backgroundColor: "inherit"
}
}
})(MuiAccordionSummary);
const AccordionDetails = withStyles({
root: {
paddingTop: 0
}
})(MuiAccordionDetails);
export default function App() {
return (
<div className="App">
<Formik>
<Form>
<Accordion>
<AccordionSummary>
<FormControl fullWidth>
<Field
component={TextField}
name="itemName"
placeholder="What do you want to buy?"
variant="outlined"
/>
</FormControl>
</AccordionSummary>
<AccordionDetails>
<Grid container>
<Grid item xs={2}>
<Box>
<FormControl fullWidth>
<Field
component={TextField}
name="quantity"
label="Qty"
type="number"
variant="outlined"
size="small"
/>
</FormControl>
</Box>
</Grid>
<Grid item xs={2}>
<Box pl={1}>
<FormControl fullWidth>
<Field
component={TextField}
name="volume"
label="Vol"
type="number"
variant="outlined"
size="small"
/>
</FormControl>
</Box>
</Grid>
<Grid item xs={2}>
<Box pl={1}>
<FormControl label="Type" size="small" fullWidth>
<Field
component={Select}
name="volumeType"
as="select"
variant="outlined"
>
<MenuItem value="g">grams</MenuItem>
<MenuItem value="kg">kg</MenuItem>
<MenuItem value="ml">ml</MenuItem>
<MenuItem value="cl">cl</MenuItem>
<MenuItem value="litre">litre</MenuItem>
<MenuItem value="pint">pint</MenuItem>
<MenuItem value="pack">pack</MenuItem>
</Field>
</FormControl>
</Box>
</Grid>
<Grid item xs={4}>
<Box pl={1}>
<FormControl fullWidth>
<Field
component={TextField}
name="brandName"
label="Brand"
variant="outlined"
size="small"
/>
</FormControl>
</Box>
</Grid>
<Grid item xs={2}>
<Box pl={1}>
<Button
type="submit"
variant="contained"
color="primary"
disableElevation
fullWidth
>
Add
</Button>
</Box>
</Grid>
</Grid>
</AccordionDetails>
</Accordion>
</Form>
</Formik>
</div>
);
}
The only way I could get this to work without creating a massive performance hit was the following:
import Accordion from "#material-ui/core/Accordion";
import AccordionDetails from "#material-ui/core/AccordionDetails";
import AccordionSummary from "#material-ui/core/AccordionSummary";
import Typography from "#material-ui/core/Typography";
import ExpandMoreIcon from "#material-ui/icons/ExpandMore";
import React, { useState } from "react";
export default function ControlledAccordions() {
const [expanded, setExpanded] = useState("");
const handleChange = (panel) => () => {
setExpanded(panel);
};
return (
<div>
<Accordion
expanded={expanded === "panel1"}
onChange={handleChange("panel1")}
>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography>General settings</Typography>
<Typography>I am an accordion</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography>
Nulla facilisi. Phasellus sollicitudin nulla et quam mattis feugiat.
Aliquam eget maximus est, id dignissim quam.
</Typography>
</AccordionDetails>
</Accordion>
</div>
);
}

How to make Material-UI Dialog work in React

I am using material-UI for my project and I want to use Dialog but Dialog not working without any error. I am using react with material design. I try many things but still not working. I am using react with material design.i want to open form in Dialog.
App.tsx
import React from "react";
import logo from "./logo.svg";
import "./style.scss";
import {
Button,
FormControl,
TextField,
Grid,
Container
} from "#material-ui/core";
import CreateDialog from "./Components/UserLoginSignUp/Signup";
function App() {
return (
<Container>
<div className="App">
<CreateDialog />
sdfsdf
</div>
</Container>
);
}
export default App;
Signup.tsx
import React, { Fragment } from "react";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle
} from "#material-ui/core";
import { FormControl, TextField, Grid, Container } from "#material-ui/core";
import { Component } from "react";
export default class extends Component {
state = {
open: false
};
handleToggle = () => {
this.setState({
open: !this.state.open
});
};
render() {
const { open } = this.state;
return (
<Fragment>
<Button>add</Button>
<Dialog aria-labelledby="form-dialog-title" open={open}>
<DialogTitle id="form-dialog-title">Set backup account</DialogTitle>
<DialogContent>
<DialogContentText>form</DialogContentText>
<Grid container spacing={3}>
<Grid item xs={12} sm={6} id="content_side_userLS">
<Grid>
{" "}
<h1>Signup</h1>
<p>
Invest with next-generation wealth building & investment
platform.
</p>
</Grid>
</Grid>
<Grid item xs={12} sm={6}>
<form noValidate autoComplete="off">
<FormControl className="input_field" fullWidth>
<TextField id="standard-basic" label="Full Name" />
</FormControl>
<FormControl className="input_field" fullWidth>
<TextField
id="standard-basic"
label="Enter Email/Mobile Number"
/>
</FormControl>
<FormControl className="input_field" fullWidth>
{" "}
<TextField id="standard-basic" label="Password" />
</FormControl>
<FormControl className="input_field" fullWidth>
{" "}
<Button variant="contained" color="primary">
{" "}
CONTINUE{" "}
</Button>
</FormControl>
</form>
</Grid>
</Grid>
</DialogContent>
<DialogActions>
<Button>Subscribe</Button>
</DialogActions>
</Dialog>
</Fragment>
);
}
}
You didn't bind the handler function handleToggle to the button.
<Button onClick={this.handleToggle}>add</Button>
You need an onClose callback handler to close the dialog, and it seems you can share the same handler with onClick.
handler = () => {
this.setState({
open: !this.state.open
});
};
<Dialog
aria-labelledby="form-dialog-title"
open={open}
onClose={this.handler}
>
Try it online:

Categories

Resources