I have a couple blocks of code that sets the state of by the user enter a value into and input and even checking a checkbox. They are both throwing the classic SyntheticEvent warning:
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property buttons on a released/nullified synthetic event.
I have tried chacheing and e.persist() and its still throwing the warning on the onChange events:
const handleChange = (e) => {
e.persist();
const { name, checked } = e.target;
setHolidayData((prevState) => ({ ...prevState, [name]: checked }));
};
const updateValues = (e) => {
e.persist();
const { name, value } = e.target;
setHolidayData((prevState) => ({ ...prevState, [name]: value }));
};
These change events are on the inputs and check boxes respectively. What am i doing wrong here that the warnings are still being thrown?
Entire Component Code:
import React, { useState, useEffect, useCallback } from 'react';
import { makeStyles, withStyles } from "#material-ui/core/styles";
import _ from "lodash";
import Slide from "#material-ui/core/Slide";
import Button from '#material-ui/core/Button';
import Dialog from '#material-ui/core/Dialog';
import MuiDialogTitle from '#material-ui/core/DialogTitle';
import MuiDialogContent from '#material-ui/core/DialogContent';
import MuiDialogActions from '#material-ui/core/DialogActions';
import IconButton from '#material-ui/core/IconButton';
import CloseIcon from '#material-ui/icons/Close';
import Typography from '#material-ui/core/Typography';
import TextField from '#material-ui/core/TextField';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import Checkbox from '#material-ui/core/Checkbox';
import DateFnsUtils from '#date-io/date-fns';
import {
MuiPickersUtilsProvider,
KeyboardDatePicker,
} from '#material-ui/pickers';
import moment from 'moment';
import { toast } from 'react-toastify';
import * as actions from "../../../Redux/Actions";
import { useDispatch, useSelector } from 'react-redux';
const Transition = React.forwardRef(function Transition(props, ref) {
return <Slide direction="down" ref={ref} {...props} />;
});
const styles = (theme) => ({
root: {
margin: 0,
padding: theme.spacing(2),
},
closeButton: {
position: 'absolute',
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500],
},
});
const DialogTitle = withStyles(styles)((props) => {
const { children, classes, onClose, ...other } = props;
return (
<MuiDialogTitle disableTypography className={classes.root} {...other}>
<Typography variant="h6">{children}</Typography>
{onClose ? (
<IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
<CloseIcon />
</IconButton>
) : null}
</MuiDialogTitle>
);
});
const DialogContent = withStyles((theme) => ({
root: {
padding: theme.spacing(2),
},
}))(MuiDialogContent);
const DialogActions = withStyles((theme) => ({
root: {
margin: 0,
padding: theme.spacing(1),
},
}))(MuiDialogActions);
const HolidayDialog = (props) => {
const [noticeModal, setNoticeModal] = useState(props.open);
const [selectedDate, setSelectedDate] = useState(new Date());
const [holidayData, setHolidayData] = useState({});
const dispatch = useDispatch();
useEffect(() => {
setSelectedDate(moment(props.data.HolidayDate));
setNoticeModal(props.open);
setHolidayData(props.data);
}, [props.open]);
const user = useSelector(state => {
return JSON.stringify(state.main.user);
});
const handleDateChange = (date) => {
setSelectedDate(date);
};
const handleClose = () => {
props.onClose(false);
setNoticeModal(false);
};
const handleChange = (e) => {
e.persist();
const { name, checked } = e.target;
setHolidayData((prevState) => ({ ...prevState, [name]: checked }));
};
const updateValues = (e) => {
e.persist();
const { name, value } = e.target;
setHolidayData((prevState) => ({ ...prevState, [name]: value }));
};
const formSubmit = () => {
dispatch(actions.holiday_editHoliday(holidayData));
handleClose();
}
const handleSubmit = () => {
dispatch(actions.holiday_submitHoliday(holidayData));
handleClose();
}
const handleCreate = () => {
let createdHoliday = {
Active: true,
Branch: holidayData.Branch ? holidayData.Branch : '',
Close: holidayData.Close ? holidayData.Close : '',
CoOp: holidayData.CoOp ? holidayData.CoOp : false,
HolidayDate: selectedDate ? moment(selectedDate).format('MM/DD/YYYY') : moment().format('MM/DD/YYYY'),
HolidayName: holidayData.HolidayName ? holidayData.HolidayName : "",
Open: holidayData.Branch ? holidayData.Branch : '',
Phone: holidayData.Phone ? holidayData.Phone : true,
Web: holidayData.Web ? holidayData.Web : true,
Hours: holidayData.Hours ? holidayData.Hours : '',
}
dispatch(actions.holiday_createHoliday(createdHoliday));
handleClose();
}
const handlePublish = () => {
const userObj = JSON.parse(user);
const userName = `CCU\\${userObj.UserName}`;
if (userName != holidayData.SubmittedBy) {
dispatch(actions.holiday_publishHoliday(holidayData));
handleClose();
} else {
toast.error("Submitter & Publisher cannot be the same person", {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: true,
progress: undefined,
});
handleClose();
}
}
const handleDecline = () => {
dispatch(actions.holiday_declineHoliday(holidayData));
handleClose();
}
return (
<Dialog
open={noticeModal}
TransitionComponent={Transition}
keepMounted
onClose={handleClose}
aria-labelledby="notice-modal-slide-title"
aria-describedby="notice-modal-slide-description"
>
<DialogTitle id="customized-dialog-title" onClose={handleClose}>
{holidayData.HolidayName ? holidayData.HolidayName : 'Create New Holiday'}
</DialogTitle>
<form noValidate autoComplete="off" id="HolidayForm" onSubmit={(e) => { e.preventDefault(); formSubmit(); } }>
<DialogContent dividers>
<div className="row">
<div className="col">
<TextField required name="HolidayName" id="outlined-basic" label="Holiday Name" variant="outlined" onChange={updateValues} value={holidayData.HolidayName || ''} disabled={holidayData.Submitted != null}/>
</div>
<div className="col">
<TextField id="outlined-basic" name="Branch" label="Branch" variant="outlined" onChange={updateValues} value={holidayData.Branch || ''} disabled={holidayData.Submitted != null}/>
</div>
</div>
<div className="row mt-3">
<div className="col">
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
disableToolbar
variant="inline"
format="MM/dd/yyyy"
margin="normal"
id="date-picker-inline"
label="Holiday Date *"
value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change date',
}}
disabled={holidayData.Submitted != null}
/>
</MuiPickersUtilsProvider>
</div>
<div className="col">
<TextField id="outlined-basic" name="Hours" label="Hours" variant="outlined" onChange={updateValues} value={holidayData.Hours || ''} disabled={holidayData.Submitted != null}/>
</div>
</div>
{holidayData.Hours ? (
<div className="row mt-3">
<div className="col">
<TextField id="outlined-basic" name="Open" label="Open" variant="outlined" onChange={updateValues} value={holidayData.Open || ''} disabled={holidayData.Submitted != null}/>
</div>
<div className="col">
<TextField id="outlined-basic" name="Close" label="Close" variant="outlined" onChange={updateValues} value={holidayData.Close || ''} disabled={holidayData.Submitted != null}/>
</div>
</div>
) : (
<div></div>
)}
<div className="row mt-3">
<div className="col d-flex flex-column">
<FormControlLabel
control={
<Checkbox
checked={holidayData.Web || false}
value={holidayData.Web}
onChange={handleChange}
name="Web"
color="primary"
disabled={holidayData.Submitted != null}
/>
}
label="Show on Web?"
/>
<FormControlLabel
control={
<Checkbox
checked={holidayData.CoOp || false}
value={holidayData.CoOp}
onChange={handleChange}
name="CoOp"
color="primary"
disabled={holidayData.Submitted != null}
/>
}
label="CoOp Holiday?"
/>
</div>
<div className="col d-flex flex-column">
<FormControlLabel
control={
<Checkbox
checked={holidayData.Phone || false}
value={holidayData.Phone}
onChange={handleChange}
name="Phone"
color="primary"
disabled={holidayData.Submitted != null}
/>
}
label="Use in IVR?"
/>
<FormControlLabel
control={
<Checkbox
checked={holidayData.Active || true}
value={holidayData.Active}
onChange={handleChange}
disabled
name="Active"
color="primary"
/>
}
label="Active"
/>
</div>
</div>
</DialogContent>
<DialogActions className="d-flex">
{holidayData.Submitted ? (
<div className="mr-auto">
<Button variant="outlined" color="primary" onClick={handlePublish}>
Publish
</Button>
<Button variant="outlined" color="secondary" className="ml-2" onClick={handleDecline}>
Decline
</Button>
</div>
) : (
<div className="mr-auto">
<Button variant="outlined" color="primary" onClick={handleSubmit}>
Submit
</Button>
</div>
)}
<Button variant="outlined" onClick={handleClose} color="default">
Cancel
</Button>
{holidayData.Active ? (
<Button variant="outlined" color="primary" type="submit" form="HolidayForm" disabled={holidayData.Submitted != null}>
Update Holiday
</Button>
) : (
<Button variant="outlined" color="primary" onClick={handleCreate} form="HolidayForm">
Create Holiday
</Button>
)}
</DialogActions>
</form>
</Dialog>
)
}
export default HolidayDialog;
Related
I am using URL.createObjectURL to create image and pass it to an other component. In my NotificationStepper URL.createObjectURL is working just fine but in another Createwebsite component is i am getting this error TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided..
following is my NotificationStepper component.
const styles = {
transparentBar: {
backgroundColor: 'transparent !important',
boxShadow: 'none',
paddingTop: '25px',
color: '#FFFFFF'
},
dialogPaper: {
minHeight: '400px',
maxHeight: '400px',
},
};
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const useStyles = makeStyles((theme) =>
createStyles({
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: theme.spacing(2),
},
}),
);
function getSteps() {
return ['Create', 'Audience', 'Timing'];
}
function getStepContent(step, $this) {
return (
<div className="row">
<CardBox styleName="col-lg-12"
heading="">
<form className="row" noValidate autoComplete="off" style={{ "flex-wrap": "no-wrap", "flex-direction": "column" }}>
<div className="col-md-12 col-12" style={{ "margin-bottom": "15px", "display": "flex", "align-items": "center" }}>
<Tooltip title="Use featured image of the landing page here. Works on Chrome, Opera, Edge. Recommended aspect ratio 2:1. Jpg, Jpeg, PNG file types only.">
<IconButton aria-label="">
<HelpOutlineIcon />
</IconButton>
</Tooltip>
<span style={{ "width": "20%", "margin-right": "20px" }}>Banner: </span>
<div className="inputfile">
Upload
<input className='hide_file' type="file" onChange={$this.onBannerChange} />
</div>
{$this.state.banner ?
<span>{$this.state.icon.banner}</span>
: null
}
</div>
</form>
</div >
);
}
class NotificationStepper extends React.Component {
state = {
banner: '',
crop: { x: 0, y: 0 },
zoom: 1,
aspect: 1,
croppedAreaPixels: null,
croppedImage: null,
showDialog: false,
};
onBannerChange = event => {
this.setState({ banner: event.target.files[0] });
this.setState({showDialog: true})
};
onIconChange = event => {
this.setState({ icon: event.target.files[0] });
this.setState({showDialogIcon: true})
};
onCropChange = crop => {
this.setState({ crop })
};
onCropComplete = (croppedArea, croppedAreaPixels) => {
this.setState({croppedAreaPixels: croppedAreaPixels});
};
CropImageBanner = async ()=> {
const croppedImage = await getCroppedImg(
URL.createObjectURL(this.state.banner),
this.state.croppedAreaPixels,
0
);
this.setState({ banner: croppedImage });
this.closeDialog();
};
closeDialog = () => {
this.setState({showDialog: false});
}
onZoomChange = zoom => {
this.setState({ zoom })
};
render() {
const steps = getSteps();
const { activeStep } = this.state;
if (this.props.showSuccessMessage) {
console.log('dispatch');
setTimeout(() => {
this.props.hideMessage();
}, 100);
}
if (this.props.showMessage) {
console.log('dispatch');
setTimeout(() => {
this.props.hideCompaignAlert();
}, 100);
}
const { classes } = this.props;
return (
<div>
{this.state.banner ?
// <span>{$this.state.banner.name}</span>
<Dialog
classes={{paper: classes.dialogPaper }}
fullWidth={true}
maxWidth='sm'
open={this.state.showDialog}
onClose={this.closeDialog}
>
<DialogTitle>
</DialogTitle>
<DialogContent>
<div className="App-crop" >
<div className="crop-container-div">
<Cropper
image={URL.createObjectURL(this.state.banner)}
crop={this.state.crop}
zoom={this.state.zoom}
aspect={this.state.aspect}
onCropChange={this.onCropChange}
onCropComplete={this.onCropComplete}
onZoomChange={this.onZoomChange}
/>
</div>
<div className="controls">
<Slider
value={this.state.zoom}
min={1}
max={3}
step={0.1}
aria-labelledby="Zoom"
onChange={(e, zoom) => this.onZoomChange(zoom)}
/>
</div>
</div>
</DialogContent>
<DialogActions>
<Button onClick={() => this.closeDialog()} color="secondary">
Cancel
</Button>
<Button onClick={() =>
this.CropImageBanner()
} color="primary">
Crop
</Button>
</DialogActions>
</Dialog>
:
null
}
<Stepper className="MuiPaper-root-custom" activeStep={activeStep} orientation="vertical">
{steps.map((label, index) => {
return (
<Step key={label}>
<StepLabel>{label}</StepLabel>
<StepContent className="pb-3">
<Typography>{getStepContent(index, this)}</Typography>
<div className="mt-2">
<div>
<Button
disabled={activeStep === 0}
onClick={this.handleBack}
className="jr-btn"
>
Back
</Button>
<Button
variant="contained"
color="primary"
onClick={this.handleNext}
className="jr-btn"
>
{activeStep === steps.length - 1 ? 'Finish' : 'Next'}
</Button>
</div>
</div>
</StepContent>
</Step>
);
})}
</Stepper>
{activeStep === steps.length && (
// <Paper square elevation={0} className="p-2">
/*<Typography>All steps completed - you"re finished</Typography>*/
<div>
<Button onClick={this.sendNotification} disabled={!this.isFormValid} color="primary" style={{ "align-self": "flex-end", "border": "1px solid", "margin-left": "10px", "margin-bottom": "40px" }} size="small" className="col-md-2 col-2">Create</Button>
<Button onClick={this.handleReset} color="primary" style={{ "align-self": "flex-end", "border": "1px solid", "margin-left": "10px", "margin-bottom": "40px" }} size="small" className="col-md-2 col-2" color="primary">Reset</Button>
)}
{this.props.showMessage && NotificationManager.error(this.props.alertMessage) ?
<NotificationContainer /> : null
}
{this.props.showSuccessMessage && NotificationManager.success(this.props.successMessage)}
<NotificationContainer />
</div>
);
}
}
const mapDispatchToProps = dispatch => ({
showCompaignAlert: (message) => dispatch(showCompaignAlert(message)),
CreateCampaign: (data) => dispatch(CreateCampaign(data)),
hideMessage: () => dispatch(hideMessage()),
hideCompaignAlert: () => dispatch(hideCompaignAlert()),
showCampaignLoader: () => dispatch(showCampaignLoader())
});
const mapStateToProps = state => ({
loader: state.Campaigns.loader,
allWebsites: state.Websites.allWebsites,
alertMessage: state.Campaigns.alertMessage,
showMessage: state.Campaigns.showMessage,
successMessage: state.Campaigns.successMessage,
showSuccessMessage: state.Campaigns.showSuccessMessage,
});
export default withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles) (NotificationStepper)));
and following is my CreateWebsite
import React from "react";
import Button from "#material-ui/core/Button";
import Dialog from "#material-ui/core/Dialog";
import Slide from "#material-ui/core/Slide";
import DialogTitle from "#material-ui/core/DialogTitle";
import DialogContent from "#material-ui/core/DialogContent";
import DialogActions from "#material-ui/core/DialogActions";
import FormControl from "#material-ui/core/FormControl";
import TextField from "#material-ui/core/TextField";
import {connect} from "react-redux";
import {createWebsite, hideSuccessMessage, hideAlertCreateWebsite} from "../../../actions/Websites";
import {NotificationContainer, NotificationManager} from "react-notifications";
import InputAdornment from "#material-ui/core/InputAdornment";
import IconButton from "#material-ui/core/IconButton";
import getCroppedImg from "../Send Notification/cropImage";
import Cropper from "react-easy-crop";
import Slider from "#material-ui/core/Slider";
import {withStyles} from "#material-ui/core/styles";
const styles = {
transparentBar: {
backgroundColor: 'transparent !important',
boxShadow: 'none',
paddingTop: '25px',
color: '#FFFFFF'
},
dialogPaper: {
minHeight: '400px',
maxHeight: '400px',
},
};
class CreateWebsiteComponent extends React.Component {
state = {
title: '',
url: '',
logo: '',
showDialog: false,
crop: { x: 0, y: 0 },
zoom: 1,
aspect: 1,
croppedAreaPixels: null,
croppedImage: null,
};
handleChange = name => event => {
this.setState({
[name]: event.target.value,
});
};
onFileChange = event => {
this.setState({ logo: event.target.files[0] });
this.setState({ showDialog: true})
};
createWebsite = (title, url, logo) => {
let temp = 'https://' + url;
this.props.createWebsite({title, url , logo})
};
onCropChange = crop => {
this.setState({ crop })
};
onCropComplete = (croppedArea, croppedAreaPixels) => {
this.setState({croppedAreaPixels: croppedAreaPixels});
};
closeDialog = () => {
this.setState({showDialog: false});
};
onZoomChange = zoom => {
this.setState({ zoom })
};
CropImageBanner = async ()=> {
const croppedImage = await getCroppedImg(
URL.createObjectURL(this.state.logo),
this.state.croppedAreaPixels,
0
);
this.setState({ logo: croppedImage });
this.closeDialog();
};
render() {
if (this.props.showSuccessMessage) {
setTimeout(() => {
this.props.hideSuccessMessage();
}, 100);
}
if (this.props.showAlertCreateWebsite_) {
setTimeout(() => {
this.props.hideAlertCreateWebsite();
}, 100);
}
const { title, url, logo} = this.state;
const openDialog = this.props.openDialog;
const { classes } = this.props;
return (
<div>
<Dialog
classes={{paper: classes.dialogPaper }}
fullWidth={true}
maxWidth='md'
open={this.state.showDialog}
onClose={this.closeDialog}
>
<DialogTitle>
</DialogTitle>
<DialogContent>
<div className="App-crop" >
<div className="crop-container-div">
<Cropper
image={this.state.log}
crop={this.state.crop}
zoom={this.state.zoom}
aspect={this.state.aspect}
onCropChange={this.onCropChange}
onCropComplete={this.onCropComplete}
onZoomChange={this.onZoomChange}
/>
</div>
<div className="controls">
<Slider
value={this.state.zoom}
min={1}
max={3}
step={0.1}
aria-labelledby="Zoom"
onChange={(e, zoom) => this.onZoomChange(zoom)}
/>
</div>
</div>
</DialogContent>
<DialogActions>
<Button onClick={() => this.closeDialog()} color="secondary">
Cancel
</Button>
<Button onClick={() =>
this.CropImageBanner()
} color="primary">
Crop
</Button>
</DialogActions>
</Dialog>
<Dialog
open={openDialog}
onClose={this.props.closeDialog}
>
<DialogTitle>
{"Create Website"}
</DialogTitle>
<DialogContent>
<FormControl className="w-100">
<TextField
style={{'margin-right': "10px"}}
className="col-md-11 col-11"
id="name"
label="Title"
value={this.state.title}
onChange={this.handleChange('title')}
margin="normal"
fullWidth
/>
<TextField
style={{'margin-right': "10px"}}
className="col-md-11 col-11"
id="name"
label="URL"
value={this.state.url}
onChange={this.handleChange('url')}
margin="normal"
fullWidth
InputProps={{
startAdornment: (
<InputAdornment className='positionEnd' position="start">
https://
</InputAdornment>
),
}}
/>
<div style={{"margin-top": "20px"}} className='col-md-11 col-sm-12 col-12 flex-class-custom'>
<span style={{"margin-right": "20px"}}>Icon: </span>
<div className="inputfile">
Upload
<input className='hide_file' style={{"width": "80%"}} type="file" onChange={this.onFileChange} />
</div>
{this.state.logo ?
<span>{this.state.logo.name}</span>
: null
}
</div>
</FormControl>
</DialogContent>
<DialogActions>
<Button onClick={this.props.closeDialog} color="secondary">
Cancel
</Button>
<Button onClick={() => this.createWebsite(title, url , logo)
} color="primary">
Create
</Button>
</DialogActions>
</Dialog>
{this.props.showAlertCreateWebsite_ && NotificationManager.error(this.props.alertMessage)}
<NotificationContainer/>
{this.props.showSuccessMessage && NotificationManager.success(this.props.successMessage)}
<NotificationContainer/>
</div>
)
}
}
const mapDispatchToProps = dispatch => ({
createWebsite: (payload) => dispatch(createWebsite(payload)),
hideSuccessMessage: () => dispatch(hideSuccessMessage()),
hideAlertCreateWebsite: () => dispatch(hideAlertCreateWebsite())
});
const mapStateToProps = state => ({
loader : state.Websites.loader ,
alertMessage : state.Websites.alertMessage ,
showAlertCreateWebsite_ : state.Websites.showAlertCreateWebsite_,
showSuccessMessage : state.Websites.showSuccessMessage,
successMessage : state.Websites.successMessage
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(CreateWebsiteComponent));
// export default CreateWebsiteComponent;
I'm trying to use S3 service to upload an image and it's telling me that certain variables aren't defined when I have defined them. I have imported axios and all the other stuff that are required
import React, { useState } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import Grid from "#material-ui/core/Grid";
import Button from "#material-ui/core/Button";
import Card from "#material-ui/core/Card";
import TextField from "#material-ui/core/TextField";
import CreateIcon from "#material-ui/icons/Create";
import Box from "#material-ui/core/Box";
import CardMedia from "#material-ui/core/CardMedia";
import MuiAlert from "#material-ui/lab/Alert";
import Snackbar from "#material-ui/core/Snackbar";
import { withStyles } from "#material-ui/core/styles";
import { makeStyles } from "#material-ui/core/styles";
import Chip from "#material-ui/core/Chip";
import Avatar from "#material-ui/core/Avatar";
import Slider from "#material-ui/core/Slider";
import Typography from "#material-ui/core/Typography";
import InputAdornment from "#material-ui/core/InputAdornment";
import { connect } from "react-redux";
function mapStateToProps(state) {
return {};
}
const useStyles = makeStyles((theme) => ({
root: {
"& > *": {
margin: theme.spacing(1),
marginLeft: theme.spacing(15),
},
},
input: {
display: "none",
},
}));
const useSliderStyles = makeStyles({
root: {
width: 250,
},
input: {
width: 100,
},
});
const UploadButton = () => {
const classes = useStyles();
return (
<div className={classes.root}>
<input
accept='image/*'
className={classes.input}
id='contained-button-file'
multiple
type='file'
/>
<label htmlFor='contained-button-file'>
<Button variant='contained' color='primary' component='span'>
Upload
</Button>
</label>
</div>
);
};
const StyledCard = withStyles({
root: { height: 600, width: 350 },
})(Card);
const PetitionForm = () => {
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [open, setOpen] = useState(false);
const [petition, validPetition] = useState(false);
const [noTitle, titleError] = useState(false);
const [noDescription, descriptionError] = useState(false);
const [hashtag, setHashtag] = useState("");
const [arrayOfHashtags, addHashtag] = useState([]);
const [money, setMoney] = React.useState(500);
const slider = useSliderStyles();
const handleTitleChange = (event) => setTitle(event.target.value);
const handleDescriptionChange = (event) => setDescription(event.target.value);
const handleClose = (event, reason) => {
if (reason === "clickaway") {
return;
}
};
const Alert = (props) => (
<MuiAlert elevation={6} variant='filled' {...props} />
);
const clearField = (event) => {
setOpen(true);
if (title.length > 0 && description.length > 0) {
validPetition(true);
setTitle("");
setDescription("");
addHashtag([]);
setHashtag("");
axios({
url: `call/s3/backend`,
method: "post",
data: {
images: imageArray.toByteArray(),
},
})
.then((res) => {
imageUrlArr = res.data;
axios({
url: `api/petition_posts`,
method: "post",
data: {
petition_post: {
title: title,
description: description,
hashtags: arrayOfHashtags.join(" "),
amount_donated: 0,
media: imageUrlArr,
goal: money,
card_type: "petition",
org_profile_id: 1,
},
},
})
.then((res) => {
console.log(res.data);
})
.catch((error) => console.log(error));
})
.catch((error) => console.log(error));
}
titleError(true ? title.length === 0 : false);
descriptionError(true ? description.length === 0 : false);
};
const handleDelete = (h) => () => {
addHashtag((arrayOfHashtags) =>
arrayOfHashtags.filter((hashtag) => hashtag !== h)
);
};
const handleHashtagChange = (event) => setHashtag(event.target.value);
const handleSliderChange = (event, newValue) => {
setMoney(newValue);
};
const handleInputChange = (event) => {
setMoney(event.target.value === "" ? "" : Number(event.target.value));
};
const newHashtag = () => {
if (arrayOfHashtags.length < 3) {
addHashtag((arrayOfHashtags) => arrayOfHashtags.concat(hashtag));
} else {
console.log("Too many hashtags");
}
};
const Hashtags = arrayOfHashtags.map((h) => (
<Chip
key={h.length}
size='small'
avatar={<Avatar>#</Avatar>}
label={h}
onDelete={handleDelete(h)}
/>
));
return (
<StyledCard>
<Box mt={1}>
<Grid container justify='center'>
<TextField
id='outlined-multiline-static'
multiline
rows={1}
variant='outlined'
placeholder='Title'
value={title}
onChange={handleTitleChange}
helperText={
open // only displays helper text if button has been clicked and fields haven't been filled
? !noTitle || petition
? ""
: "Can't be an empty field"
: ""
}
/>
</Grid>
</Box>
<Box mt={1}>
<Grid container justify='center'>
<CardMedia title='Petition'>
<UploadButton />
</CardMedia>
</Grid>
</Box>
<div className={slider.root}>
<Typography>Amount to raise</Typography>
<Box>
<Grid container justify='center'>
<Slider
min={500}
max={10000}
value={typeof money === "number" ? money : 0}
onChange={handleSliderChange}
aria-labelledby='input-slider'
/>
<TextField
className={slider.input}
value={money}
onChange={handleInputChange}
InputProps={{
startAdornment: (
<InputAdornment position='start'>$</InputAdornment>
),
}}
helperText={
money < 500 || money > 10000
? "Please enter a value between 500 and 10000"
: ""
}
/>
</Grid>
</Box>
</div>
<Box mt={1} mb={1}>
<Grid container justify='center'>
<TextField
size='small'
inputProps={{
style: { fontSize: 15 },
}}
id='outlined-multiline-static'
multiline
rows={1}
placeholder='Hashtags'
variant='outlined'
value={hashtag}
onChange={handleHashtagChange}
helperText={
arrayOfHashtags.length === 3
? "You reached the maximum amount of hashtags"
: ""
}
/>
<Button color='primary' onClick={newHashtag}>
Create!
</Button>
{arrayOfHashtags.length > 0 ? Hashtags : ""}
</Grid>
</Box>
<Box mt={1} justify='center'>
<Grid container justify='center'>
<TextField
size='small'
inputProps={{
style: { fontSize: 15 },
}}
id='outlined-multiline-static'
multiline
rows={5}
placeholder='Description'
variant='outlined'
value={description}
onChange={handleDescriptionChange}
helperText={
// only displays helper text if button has been clicked and fields haven't been filled
open
? !noDescription || petition
? ""
: "Can't be an empty field"
: ""
}
/>
</Grid>
</Box>
<Box mt={1}>
<Grid container justify='center'>
<Button onClick={clearField}>
<CreateIcon />
Create Petition!
</Button>
{open && petition && (
<Snackbar open={open} autoHideDuration={2000} onClose={handleClose}>
<Alert severity='success'>
You have successfully create a petition!
</Alert>
</Snackbar>
)}
{open && !petition && (
<Snackbar open={open} autoHideDuration={2000} onClose={handleClose}>
<Alert severity='error'>You're missing one or more fields</Alert>
</Snackbar>
)}
</Grid>
</Box>
</StyledCard>
);
};
export default connect(mapStateToProps)(PetitionForm);
This is the error I'm getting, someone mentioned something about the scope and I think that shouldn't matter when I'm trying to assign a value to a variable as far I as know
Line 109:19: 'imageArray' is not defined no-undef
Line 113:11: 'imageUrlArr' is not defined no-undef
Line 123:24: 'imageUrlArr' is not defined no-undef
Search for the keywords to learn more about each error.
I'm using the Select component on #material-ui/core, but I'm having the following problem:
Cannot read property 'offsetWidth' of null
Can you help me out?
Link: codesandbox
Code:
import React from "react";
import {
Button,
DialogTitle,
Dialog,
DialogContent,
DialogActions,
TextField,
FormControl,
InputLabel,
MenuItem,
Select
} from "#material-ui/core";
function AddUserModal(props) {
const inputLabelTypeRole = React.useRef(null);
const { open, onClose } = props;
const [state, setState] = React.useState({
labelWidthTypeRole: 0,
name: ""
});
let { labelWidthTypeRole } = state;
React.useEffect(() => {
setState({
...state,
labelWidthTypeRole: inputLabelTypeRole.current.offsetWidth
});
}, []);
const onChange = name => ({ target: { value } }) => {
setState({
...state,
[name]: value
});
};
const [currency, setCurrency] = React.useState(false);
const handleChange = event => {
setCurrency(event.target.value);
};
return (
<Dialog
fullWidth
maxWidth="md"
open={open}
onClose={onClose}
aria-labelledby="max-width-dialog-title"
>
<DialogTitle id="form-dialog-title" style={{ alignSelf: "center" }}>
Add User
</DialogTitle>
<DialogContent>
<div style={{ margin: 5 }}>
<TextField
margin="dense"
id="name"
label="Name"
type="Name"
fullWidth
variant="outlined"
onChange={onChange("name")}
/>
</div>
<div style={{ margin: 5 }}>
<FormControl variant="outlined" fullWidth size="small">
<InputLabel
ref={inputLabelTypeRole}
id="demo-simple-select-outlined-label"
>
Role
</InputLabel>
<Select
labelId="demo-simple-select-outlined-label"
id="demo-simple-select-outlined"
labelWidth={labelWidthTypeRole}
value={false}
>
<MenuItem value={false}>Report</MenuItem>
<MenuItem value>Report Web hook</MenuItem>
</Select>
</FormControl>
</div>
<div style={{ margin: 5 }}>
<TextField
id="outlined-select-currency"
select
label="Select"
helperText="Please select your currency"
variant="outlined"
fullWidth
value={currency}
onChange={handleChange}
>
<MenuItem value={false}>Report</MenuItem>
<MenuItem value>Report Web hook</MenuItem>
</TextField>
</div>
</DialogContent>
<DialogActions>
<Button onClick={onClose} color="primary" variant="contained">
Create
</Button>
</DialogActions>
</Dialog>
);
}
export default function App() {
const [open, setOpen] = React.useState(false);
return (
<div className="App">
<AddUserModal open={open} onClose={() => setOpen(false)} />
<button onClick={() => setOpen(true)}>Open</button>
</div>
);
}
The error is resolved very simply: remove "current" in useEffect hook:
React.useEffect(() => {
setState({
...state,
labelWidthTypeRole: inputLabelTypeRole.**current**.offsetWidth
});
}, []);
Because in the example that you used there are several components, but you have one component and "current" is superfluous.
I'm kinda new to react and was wondering how to internally redirect your pages in reactjs. I have two pages called register and register2. In register page, I just check if the email exists in the database or not and if it doesn't exist then it redirects to register2 page for creating the full account with username and password. However, in the address bar, it kinda looks ugly to show something like register2. So I was wondering if there is any way through which I can internally redirect without changing the address in the address bar to register2 such that it stays as register throughout the whole account creation process.
I created a codesandbox to show the issue
register.js
import React, { useState } from "react";
import { Formik } from "formik";
import TextField from "#material-ui/core/TextField";
import * as Yup from "yup";
import Avatar from "#material-ui/core/Avatar";
import Button from "#material-ui/core/Button";
import CssBaseline from "#material-ui/core/CssBaseline";
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";
function Copyright() {
return (
<Typography variant="body2" color="textSecondary" align="center">
<Link color="inherit" href="sad">
New1
</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%",
marginTop: theme.spacing(1)
},
submit: {
margin: theme.spacing(3, 0, 2)
}
}));
const Reg = props => {
const classes = useStyles();
const [loginError, setLoginError] = useState("");
const [changed, setChanged] = useState(false);
const [newpage, setNew] = useState(false);
const handleSubmit = async (values, { setSubmitting }) => {
const { email } = values;
var body = {
email: email
};
console.log(body);
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(body)
};
const url = "/api/emailcheck";
try {
const response = await fetch(url, options);
const text = await response.text();
setSubmitting(false);
setChanged(false);
setNew(true);
console.log(text);
if (newpage) {
props.history.push({
pathname: "/register2",
state: { email }
});
// props.history.push(`/register2/${email}`);
} else if (text === "exists") {
props.history.push(`/`);
} else {
setLoginError("Email is invalid");
}
} catch (error) {
console.error(error);
}
};
return (
<Formik
initialValues={{ email: "" }}
onSubmit={handleSubmit}
//********Using Yup for validation********/
validationSchema={Yup.object().shape({
email: Yup.string()
.email()
.required("Required")
})}
>
{props => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur,
handleSubmit
} = props;
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}
onSubmit={handleSubmit}
noValidate
>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
value={values.email}
label="Email Address"
name="email"
autoComplete="email"
onChange={e => {
setChanged(true);
handleChange(e);
}}
onBlur={handleBlur}
className={errors.email && touched.email && "error"}
/>
{errors.email && touched.email && (
<div className="input-feedback" style={{ color: "red" }}>
{errors.email}
</div>
)}
{!changed && loginError && (
<div style={{ color: "red" }}>
<span>{loginError}</span>
</div>
)}
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
disabled={isSubmitting}
>
Next
</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>
</>
);
}}
</Formik>
);
};
export default Reg;
register2.js
import React, { useState } from "react";
import { Formik } from "formik";
import TextField from "#material-ui/core/TextField";
import { withRouter, useHistory } from "react-router-dom";
import * as Yup from "yup";
import Avatar from "#material-ui/core/Avatar";
import Button from "#material-ui/core/Button";
import CssBaseline from "#material-ui/core/CssBaseline";
import Link from "#material-ui/core/Link";
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";
function Copyright() {
return (
<Typography va riant="body2" color="textSecondary" align="center">
<Link color="inherit" href="sad">
New
</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%",
marginTop: theme.spacing(1)
},
submit: {
margin: theme.spacing(3, 0, 2)
}
}));
const Reg2 = props => {
const classes = useStyles();
const [loginError, setLoginError] = useState("");
const history = useHistory();
const [changed, setChanged] = useState(false);
const handleSubmit = async (values, { setSubmitting }) => {
const { username, password } = values;
var body = {
username: username,
password: password,
email: history.location.state.email
};
console.log(body);
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(body)
};
const url = "/api/register";
try {
const response = await fetch(url, options);
const text = await response.text();
setSubmitting(false);
setChanged(false);
console.log(text);
if (text === "verifyemail") {
props.history.push({
pathname: "/verifyOtp",
state: { email: body.email }
});
// props.history.push(`/verifyOtp/${username}`);
} else {
setLoginError("Username or Password is incorrect");
}
} catch (error) {
console.error(error);
}
};
return (
<Formik
initialValues={{ username: "", password: "", confirmPassword: "" }}
onSubmit={handleSubmit}
//********Using Yup for validation********/
validationSchema={Yup.object().shape({
username: Yup.string().required("Required"),
password: Yup.string()
.required("No password provided.")
.min(8, "Password is too short - should be 8 chars minimum.")
.matches(/(?=.*[0-9])/, "Password must contain a number.")
.matches(
/(?=.*[●!"#$%&'()*+,\-./:;<=>?#[\\\]^_`{|}~])/,
"Password must contain a symbol."
),
confirmPassword: Yup.string()
.required("Enter to confirm password")
.oneOf([Yup.ref("password"), null], "Password do not match")
})}
>
{props => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur,
handleSubmit
} = props;
return (
<>
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Enter Info
</Typography>
<form
className={classes.form}
onSubmit={handleSubmit}
noValidate
>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="username"
value={values.username}
label="username"
name="username"
autoComplete="username"
onChange={e => {
setChanged(true);
handleChange(e);
}}
onBlur={handleBlur}
className={errors.username && touched.username && "error"}
/>
{errors.username && touched.username && (
<div className="input-feedback" style={{ color: "red" }}>
{errors.username}
</div>
)}
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
value={values.password}
label="Password"
type="password"
id="password"
onBlur={handleBlur}
autoComplete="current-password"
className={errors.password && touched.password && "error"}
onChange={e => {
setChanged(true);
handleChange(e);
}}
/>
{errors.password && touched.password && (
<div className="input-feedback" style={{ color: "red" }}>
{errors.password}
</div>
)}
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="confirmPassword"
value={values.confirmPassword}
type="password"
label="Confirm Password"
id="confirmPassword"
onBlur={handleBlur}
autoComplete="confirmPassword"
className={
errors.confirmPassword &&
touched.confirmPassword &&
"error"
}
onChange={e => {
setChanged(true);
handleChange(e);
}}
/>
{errors.confirmPassword && touched.confirmPassword && (
<div className="input-feedback" style={{ color: "red" }}>
{errors.confirmPassword}
</div>
)}
{!changed && loginError && (
<div style={{ color: "red" }}>
<span>{loginError}</span>
</div>
)}
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
disabled={isSubmitting}
>
Next
</Button>
</form>
</div>
<Box mt={8}>
<Copyright />
</Box>
</Container>
</>
);
}}
</Formik>
);
};
export default withRouter(Reg2);
you could make a parent component for register and register2 and store your logic there in which component to display
function MyComponent() {
const [email, setEmail] = useState(null)
useEffect(() => {
(async () => {
const response = await yourApiCall()
setEmail(response)
})()
}, [])
return email ? <Register /> : <Register2 />
}
Initially show the register component or code of that sort.
Call an api, if the email exists, store flag value in that and do conditional rendering for another component or code of register2.
Initially, this.state.isEmailExist : false,
After api call change flag value accordingly. If true then render Register2.
const contents = if (!this.state.isEmailExist) {
return (
<Register />
);
} else {
return (
<Register2 />
)
}
return(
<div>{contents}</div>
)
Maybe you are looking for this
window.open("https://www.youraddress.com","_self");
Make sure to setup the validation.
I am trying to convert the setState into useState.
so I followed the below article and converted partially
https://medium.com/javascript-in-plain-english/state-management-with-react-hooks-no-redux-or-context-api-8b3035ceecf8- but not sure how to convert the props
but its not rendering the values.
so I debugged and put console inside useEffect.
I am getting undefind at this line, am I using useState wrongly
useEffect(() => {
console.log("useEffect setspHeight--->", setspHeight);
can you let me know how to fix it and do I need to make any other changes for react hooks
class component code
import React, { Fragment, useState, Component } from 'react';
import styles from './styles';
import { withStyles } from '#material-ui/core/styles';
import classnames from 'classnames';
import ExpandMoreIcon from '#material-ui/icons/ExpandMore';
import IconButton from '#material-ui/core/IconButton';
import Button from '#material-ui/core/Button';
import ExpansionPanel from '#material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '#material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '#material-ui/core/ExpansionPanelDetails';
import Typography from '#material-ui/core/Typography';
import Drawer from '#material-ui/core/Drawer';
import AppBar from '#material-ui/core/AppBar';
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import Radio from '#material-ui/core/Radio';
import RadioGroup from '#material-ui/core/RadioGroup';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import FormControl from '#material-ui/core/FormControl';
import FormLabel from '#material-ui/core/FormLabel';
import Checkbox from '#material-ui/core/Checkbox';
import { MuiThemeProvider, createMuiTheme } from '#material-ui/core/styles';
import dataStyles from '../../../../styles.css';
function TabContainer(props) {
return (
<Typography component="div" style={{ padding: 8 * 3 }}>
{props.children}
</Typography>
);
}
const radioValues = [
{
label: 'Select All Providers for This Category',
value: 'PRO',
},
];
class SportsExpansion extends Component {
state = {
value: 0,
spHeight: [],
spLength: '',
};
componentDidMount() {
this.setState({ spHeight: this.props.spHeight });
if (
this.props.spHeight.filter(
check => check.spWeight === 'One'
).length > 0
) {
this.setState({ value: 0 });
} else if (
this.props.spHeight.filter(
check => check.spWeight === 'Two'
).length > 0
) {
this.setState({ value: 1 });
}
}
handleChange = (event, value) => {
console.log('handleChange -value', value);
this.setState({ value });
};
handleSportsRadioValueChange = (category, value) => {
console.log('handleSportsRadioValueChange -category', category);
console.log('handleSportsRadioValueChange -value', value);
this.setState({ spLength: value });
};
render() {
const { classes, data } = this.props;
let udVal = '';
let starVal = '';
udVal = data.udVals ? data.udVals[0].number : '';
starVal = data.starVals ? data.starVals[0].number : '';
const { canEdit, value } = this.state;
const { spHeight } = this.state;
return (
<div>
<AppBar
className={classes.benchmarkTabHeader}
position="static"
color="default"
>
<Tabs
onChange={this.handleChange}
variant="scrollable"
scrollButtons="on"
indicatorColor="primary"
textColor="primary"
style={{ display: 'block' }}
classes={{
indicator: classes.tabsIndicator,
scrollButtons: classes.MuiPrivateTabScrollButton,
}}
>
<Tab
style={{
display:
this.state.spHeight.filter(
check =>
check.spWeight === 'One'
).length === 0
? 'none'
: '',
color: value == 0 ? '#1976D2' : '#66696C',
}}
label={`Groups (${
this.state.spHeight.filter(
check =>
check.spWeight === 'One'
).length
})`}
icon={
<FontAwesomeIcon style={{ display: 'block' }} />
}
classes={{
root: classes.tabRoot,
selected: classes.tabSelected,
wrapper: classes.alignment,
}}
/>
<Tab
style={{
display:
this.state.spHeight.filter(
check =>
check.spWeight ===
'Two'
).length === 0
? 'none'
: '',
color: value == 1 ? '#1976D2' : '#66696C',
}}
label={`Two (${
this.state.spHeight.filter(
check =>
check.spWeight ===
'Two'
).length
})`}
icon={
<FontAwesomeIcon style={{ display: 'block' }} />
}
classes={{
root: classes.tabRoot,
selected: classes.tabSelected,
wrapper: classes.alignment,
}}
/>
</Tabs>
</AppBar>
{value === 0 && (
<TabContainer>
<div>
{' '}
<FormControl
component="fieldset"
className={classes.formControl}
>
<FormLabel component="legend" />
<RadioGroup
aria-label="Gender"
name="gender1"
className={classes.one}
value={this.state.spLength}
onChange={e => {
this.setState({
spLength: e.target.value,
});
}}
>
{this.state.spHeight
.filter(
check =>
check.spWeight ===
'One'
)
.map((radio, radioIndex) => {
return (
<FormControlLabel
key={radioIndex}
value={radio.value}
control={<Radio />}
label={radio.label}
classes={{
label:
classes.checkboxLabel,
}}
/>
);
})}
)}
</RadioGroup>
</FormControl>
<div className="tiger-button-container">
<Button
variant="outlined"
color="primary"
size="small"
className="tiger-button-upload"
>
ghsd jkjkjk
</Button>
</div>
<Drawer
style={{ width: 500 }}
anchor="right"
open={this.state.right}
>
<div tabIndex={0} role="button"></div>
</Drawer>
</div>
</TabContainer>
)}
{value === 1 && (
<TabContainer>
<div>
<div>
<FormControl
component="fieldset"
className={classes.formControl}
>
<RadioGroup
aria-label="Gender"
name="gender1"
className={classes.one}
value={this.state.spLength}
onChange={e => {
this.setState({
spLength:
e.target.value,
});
}}
>
{this.state.spHeight
.filter(
check =>
check.spWeight ===
'Two'
)
.map((radio, radioIndex) => {
return (
<FormControlLabel
key={radioIndex}
value={radio.label}
control={<Radio />}
label={radio.label}
classes={{
label:
classes.checkboxLabel,
}}
/>
);
})}
</RadioGroup>
</FormControl>
<div className="tiger-button-container">
<Button
variant="outlined"
color="primary"
size="small"
className="tiger-button-upload"
>
ghsd jkjkjk
</Button>
</div>
</div>
</div>
</TabContainer>
)}
</div>
);
}
}
export default withStyles(styles)(SportsExpansion);
////////////////////////////////////////////////
functional component code
import React, { Fragment, useState, useEffect, Component } from 'react';
import styles from './styles';
import { withStyles } from '#material-ui/core/styles';
import classnames from 'classnames';
import ExpandMoreIcon from '#material-ui/icons/ExpandMore';
import IconButton from '#material-ui/core/IconButton';
import Button from '#material-ui/core/Button';
import ExpansionPanel from '#material-ui/core/ExpansionPanel';
import ExpansionPanelSummary from '#material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '#material-ui/core/ExpansionPanelDetails';
import Typography from '#material-ui/core/Typography';
import Drawer from '#material-ui/core/Drawer';
import AppBar from '#material-ui/core/AppBar';
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import Radio from '#material-ui/core/Radio';
import RadioGroup from '#material-ui/core/RadioGroup';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import FormControl from '#material-ui/core/FormControl';
import FormLabel from '#material-ui/core/FormLabel';
import Checkbox from '#material-ui/core/Checkbox';
import { MuiThemeProvider, createMuiTheme } from '#material-ui/core/styles';
import dataStyles from '../../../../styles.css';
function TabContainer(props) {
return (
<Typography component="div" style={{ padding: 8 * 3 }}>
{props.children}
</Typography>
);
}
const radioValues = [
{
label: 'Select All Providers for This Category',
value: 'PRO',
},
];
//class SportsExpansion extends Component {
const SportsExpansion = (props) => {
const [value, setValue] = useState(0);
const [spHeight, setspHeight] = useState([]);
const [spLength, setspLength] = useState('');
// const { classes, data } = this.props;
const { classes, data } = props;
let udVal = '';
let starVal = '';
udVal = data.udVals ? data.udVals[0].number : '';
starVal = data.starVals ? data.starVals[0].number : '';
// const { canEdit, value } = this.state;
// const { spHeight } = this.state;
useEffect(() => {
// code to run on component mount
console.log("useEffect setspHeight--->", setspHeight);
//this.setState({ spHeight: this.props.spHeight });
setspHeight(spHeight);
if (
spHeight.filter(
check => check.spWeight === 'One'
).length > 0
) {
useState({ value: 0 });
} else if (
spHeight.filter(
check => check.spWeight === 'Two'
).length > 0
) {
useState({ value: 1 });
}
}, [])
//handleChange = (event, value) => {
const handleChange = (event, value) => {
console.log('handleChange -value', value);
useState({ value });
};
// handleSportsRadioValueChange = (category, value) => {
const handleSportsRadioValueChange = (category, value) => {
console.log('handleSportsRadioValueChange -category', category);
console.log('handleSportsRadioValueChange -value', value);
useState({ spLength: value });
};
return (
<div>
<AppBar
className={classes.benchmarkTabHeader}
position="static"
color="default"
>
<Tabs
onChange={this.handleChange}
variant="scrollable"
scrollButtons="on"
indicatorColor="primary"
textColor="primary"
style={{ display: 'block' }}
classes={{
indicator: classes.tabsIndicator,
scrollButtons: classes.MuiPrivateTabScrollButton,
}}
>
<Tab
style={{
display:
//this.state.spHeight.filter(
spHeight.filter(
check =>
check.spWeight === 'One'
).length === 0
? 'none'
: '',
color: value == 0 ? '#1976D2' : '#66696C',
}}
label={`Groups (${
//this.state.spHeight.filter(
spHeight.filter(
check =>
check.spWeight === 'One'
).length
})`}
icon={
<FontAwesomeIcon style={{ display: 'block' }} />
}
classes={{
root: classes.tabRoot,
selected: classes.tabSelected,
wrapper: classes.alignment,
}}
/>
<Tab
style={{
display:
//this.state.spHeight.filter(
spHeight.filter(
check =>
check.spWeight ===
'Two'
).length === 0
? 'none'
: '',
color: value == 1 ? '#1976D2' : '#66696C',
}}
label={`Two (${
//this.state.spHeight.filter(
spHeight.filter(
check =>
check.spWeight ===
'Two'
).length
})`}
icon={
<FontAwesomeIcon style={{ display: 'block' }} />
}
classes={{
root: classes.tabRoot,
selected: classes.tabSelected,
wrapper: classes.alignment,
}}
/>
</Tabs>
</AppBar>
{value === 0 && (
<TabContainer>
<div>
{' '}
<FormControl
component="fieldset"
className={classes.formControl}
>
<FormLabel component="legend" />
<RadioGroup
aria-label="Gender"
name="gender1"
className={classes.one}
value={//this.state.spLength
spLength}
onChange={e => {
useState({
spLength: e.target.value,
});
}}
>
{//this.state.spHeight
spHeight
.filter(
check =>
check.spWeight ===
'One'
)
.map((radio, radioIndex) => {
return (
<FormControlLabel
key={radioIndex}
value={radio.value}
control={<Radio />}
label={radio.label}
classes={{
label:
classes.checkboxLabel,
}}
/>
);
})}
)}
</RadioGroup>
</FormControl>
<div className="tiger-button-container">
<Button
variant="outlined"
color="primary"
size="small"
className="tiger-button-upload"
>
ghsd jkjkjk
</Button>
</div>
{/*<Drawer
style={{ width: 500 }}
anchor="right"
open={
//this.state.right
right}
>
<div tabIndex={0} role="button"></div>
</Drawer>*/}
</div>
</TabContainer>
)}
{value === 1 && (
<TabContainer>
<div>
<div>
<FormControl
component="fieldset"
className={classes.formControl}
>
<RadioGroup
aria-label="Gender"
name="gender1"
className={classes.one}
value={//this.state.spLength
spLength}
onChange={e => {
useState({
spLength:
e.target.value,
});
}}
>
{//this.state.spHeight
spHeight
.filter(
check =>
check.spWeight ===
'Two'
)
.map((radio, radioIndex) => {
return (
<FormControlLabel
key={radioIndex}
value={radio.label}
control={<Radio />}
label={radio.label}
classes={{
label:
classes.checkboxLabel,
}}
/>
);
})}
</RadioGroup>
</FormControl>
<div className="tiger-button-container">
<Button
variant="outlined"
color="primary"
size="small"
className="tiger-button-upload"
>
ghsd jkjkjk
</Button>
</div>
</div>
</div>
</TabContainer>
)}
</div>
);
}
export default withStyles(styles)(SportsExpansion);
You have to replace where you call useState({ value: 1 }); to setValue(value)
You are using useState wrong. useState replaces the state object. The first value in the array is the value you can call in your component. The second value in the array replaces this.setState and sets the value of the state instance. So to use the useState hook if you had the following:
const [value, setValue] = useState(0);
you would use value in your component to reference this state instance. And you would use setValue to set the value of this state instance. So to set value to 2 you would do setValue(2).