React not closing dialog box - javascript

Im using materialUI to click a menu item that then opens a dialog box(child component) however after the dialogbox opens it wont seem to close and wont update the data for noticeModal. There are not any errors being thrown and i belive it has to do with using useEffect to setNoticeModal(props.open) for the initial state. Ive tried removing the useEffect() and throwing props.open into the default useDate() for the noticeModal however upon doing that then my dialogbox wont open anymore at all. What am i over looking here?
holidaySettings.js
...
const [dialogOpen, setDialogOpen] = React.useState(false);
const handleDialogOpen = (dataElement) => {
setDialogData(dataElement);
setDialogOpen(true);
setOpen(false);
}
...
<ClickAwayListener onClickAway={handleClose}>
<MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
<MenuItem onClick={handleDialogOpen}>Add Holiday</MenuItem>
</MenuList>
</ClickAwayListener>
...
<div className="card-body">
<div className="row">
<div className="text-left col-12">
<Styles>
<Table columns={columns} data={data} />
<HolidayDialog open={dialogOpen} onClose={handleDialogClose} data={dialogData}/>
</Styles>
</div>
</div>
</div>
...
holidayDialog.js
const HolidayDialog = (props) => {
const [noticeModal, setNoticeModal] = useState(false);
const [selectedDate, setSelectedDate] = useState(new Date());
const [holidayData, setHolidayData] = useState(props.data);
useEffect(() => {
setNoticeModal(props.open)
});
const handleDateChange = (date) => {
setSelectedDate(date);
};
const handleClose = () => {
setNoticeModal(false);
console.log(noticeModal);
};
const handleChange = (e) => {
const { name, checked } = e.target;
setHolidayData((prevState) => ({ ...prevState, [name]: checked }));
};
const updateValues = (e) => {
const { name, value } = e.target;
setHolidayData((prevState) => ({ ...prevState, [name]: value }));
}
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>
<DialogContent dividers>
<form noValidate autoComplete="off">
<div className="row">
<div className="col">
<TextField required name="HolidayName" id="outlined-basic" label="Holiday Name" variant="outlined" onChange={updateValues} value={holidayData.HolidayName || ''}/>
</div>
<div className="col">
<TextField id="outlined-basic" name="Branch" label="Branch" variant="outlined" onChange={updateValues} value={holidayData.Branch || 'ALL'}/>
</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="Date picker inline"
value={selectedDate}
onChange={handleDateChange}
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
</MuiPickersUtilsProvider>
</div>
<div className="col">
<TextField id="outlined-basic" name="Hours" label="Hours" variant="outlined" onChange={updateValues} value={holidayData.Hours || 'Closed'}/>
</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"
/>
}
label="Show on Web?"
/>
<FormControlLabel
control={
<Checkbox
checked={holidayData.CoOp || false}
value={holidayData.CoOp}
onChange={handleChange}
name="CoOp"
color="primary"
/>
}
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"
/>
}
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>
</form>
</DialogContent>
<DialogActions>
<Button autoFocus onClick={handleClose} color="default">
Cancel
</Button>
<Button autoFocus onClick={handleClose} color="primary">
Create Holiday
</Button>
</DialogActions>
</Dialog>
)
}
export default HolidayDialog;

Could you try this?
I am assuming props.onClose is making dialogOpen to false on parent(holidaySettings)
const handleClose = () => {
props.onClose()
};
If props.onClose is not making dialogOpen to false on parent(holidaySettings).You can add close attribute which sets dialogOpen to false.
<HolidayDialog open={dialogOpen} close={()=>setDialogOpen(false);} onClose={handleDialogClose} data={dialogData}/>
const handleClose = () => {
props.close()
};
And passing props.open to Dialog
<Dialog
open={props.open}
/>

You are not providing any dependency to useEffect so it runs on every re-render. In your useEffect you are toggling the modal and hence the issue.
useEffect(() => {
setNoticeModal(props.open)
});//<---- issue - missing dependency
Solution - pass dependency as props.open. This makes the useEffect to run only when props.open is changed.
useEffect(() => {
setNoticeModal(props.open)
}, [props.open]); //<----- props.open

Inside the useEffect, you are resetting the noticeModal value to props.open which i believe is true?
I believe what you are trying to do is set the initial value of noticeModal.
Try changing to the code below and remove the useEffect
const [noticeModal, setNoticeModal] = useState(props.open);

Related

onChange Event not Triggered in React JS

export default function ActionRolesPage(props) {
const [authorities, setAuthorities] = useState([]);
const [name, setName] = useState("");
let list = [];
useEffect(() => {
getAuthorities();
}, []);
const getAuthorities = () => {
doGetAllAuthorities()
.then((res) => {
getValidatedData(res.data, "array").map((data) => (
list.push({ authority: data})
))
setAuthorities(list);
}).catch((e) => {
console.log(e);
})
}
const handleChange = (e) => {
console.log(e);
const { name, checked } = e.target
console.log(name,checked);
let tempUser = authorities.map((user) => (
user.authority === name ? { ...user, isChecked: checked } : user
));
setAuthorities(tempUser);
}
if(authorities.length){
console.log(authorities);
}
return (
<React.Fragment>
<Suspense fallback={<div>Loading....</div>}>
<div className="page-content">
<MetaTags>
<title>Add Role | IG One</title>
</MetaTags>
<Container fluid>
<Breadcrumb
title="Add Role"
breadcrumbItems={[{ title: "Settings" }, { title: "Roles" }, { title: "Add" }]}
/>
<Form onSubmit={handleSubmit}>
<Card>
<CardBody>
<Row className="mb-3">
<label
htmlFor="example-text-input"
className="col-md-2 col-form-label"
>
Name
</label>
<div className="col-md-8 mx-0">
<Input
className="form-control"
type="text"
name="name"
required
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Name Of User "
/>
</div>
</Row>
<br></br>
<br></br>
<Row className="mb-3">
<CardTitle>
Authorities
</CardTitle>
<div className="col-md-2">
{
authorities.map((data,index) => (
<>
<div key={index} style={{ display: "flex" }}>
<div className='col-md-10 mx-0 mt-2'>
<Input type={"checkbox"}
checked={data?.isChecked || false}
name={data.authority}
onChange={(e) => console.log(e)}
className="form-control"
style={{ cursor: "pointer", paddingLeft: "1rem" }}
/></div>
<div>
<label style={{ cursor: "pointer" }} htmlFor={data.authority} className="col-md-50 col-form-label"> {data.authority}</label>
</div>
</div>
</>
))
}
</div>
</Row>
<Row className="d-flex justify-content-center mt-4">
<Button color="dark" type='submit' className="btn-xs" style={{ width: "40%", cursor: "pointer" }}
>
Add Role
</Button>
</Row>
</CardBody>
</Card>
</Form>
</Container>
</div>
</Suspense>
</React.Fragment>
)
}
Here is the whole code. I want to handle multiple checkboxes but onChange Event not triggered. There is a function handleChange it calls when onChange triggered but in my case there is no error seen in console as well as not display any event at console please resolve my doubt.
I also need to update the form getting respose from backend is checked authority name array How to handle checked state in checkbox.
If you have created a custom component for input, pass your onChange handler as prop and call inside the component as onChage event of <input> field. Or if you used any third-party lib, then you just need to pass a callback as prop. Otherwise Try this: <input> instead of <Input>
<input type={"checkbox"}
checked={data?.isChecked || false}
name={data.authority}
onChange={(e) => console.log(e)}
className="form-control"
style={{ cursor: "pointer", paddingLeft: "1rem" }}
/>

None of the Tabs' children match with `[object Object]`. You can provide one of the following values: 0, 1

I am building header using material UI Tab Component but I see below error:
index.js:2178 Material-UI: The value provided to the Tabs component is invalid.
None of the Tabs' children match with [object Object].
You can provide one of the following values: 0, 1.
I tried console.log the newValue to see what value it is getting and I can see 0 and 1 while navigating through tabs.
Note : Removed Some Code for better visibility
Here is my component:
const Header = (props) => {
const { classes } = props;
const [value, setValue] = useState(0);
const [modalIsOpen, setIsOpen] = React.useState(false);
const openModal = () => {
setIsOpen(true);
};
const closeModal = () => {
setIsOpen(false);
};
const handleTabChange = (event, newValue) => {
console.log(newValue);
setValue({ newValue });
};
return (
<div>
<div className="topnav">
<img src={logo} className="logo" alt="Movies App Logo" />
<div className="topnav-right">
<Button variant="contained" color="default" onClick={openModal}>
Login
</Button>
</div>
<div className="topnav-right">
<Button variant="contained" color="default">
Logout
</Button>
</div>
</div>
<Modal
ariaHideApp={false}
isOpen={modalIsOpen}
onRequestClose={closeModal}
contentLabel="Login"
aria-labelledby="Modal"
aria-describedby="Modal for Login and Registration"
style={customStyles}
>
<Paper className={classes.Paper}>
<CardContent>
<Tabs
className="tabs"
value={value}
onChange={handleTabChange}
centered
>
<Tab label="Login" />
<Tab label="Register" />
</Tabs>
{value === 0 && (
<div>
<FormControl required>
<InputLabel htmlFor="username" className={classes.inputLable}>
Username
</InputLabel>
<Input
className={classes.Input}
id="username"
type="text"
username={username}
onChange={usernameChangeHandler}
/>
<FormHelperText>
<span className="red">required</span>
</FormHelperText>
</FormControl>
<br />
<br />
<FormControl required>
<InputLabel
htmlFor="loginPassword"
className={classes.inputLable}
>
Password
</InputLabel>
<Input
className={classes.Input}
id="loginPassword"
type="password"
password={password}
onChange={passwordChangeHandler}
/>
<FormHelperText>
<span className="red">required</span>
</FormHelperText>
</FormControl>
<br />
<br />
{loggedIn === true && (
<FormControl>
<span className="success-text">Login Successful!</span>
</FormControl>
)}
<br />
<br />
<Button
variant="contained"
color="primary"
onClick={loginHandler}
>
LOGIN
</Button>
</div>
)}
{value === 1 && (
<div>
<h1>something</h2>
</div>
)}
</CardContent>
</Paper>
</Modal>
</div>
);
};
export default withStyles(styles)(Header);
For some reason you enclosed the value in an object (curly braces syntax).
Replace setValue({ newValue }) with setValue(newValue).

Trying to switch between modal components using React

So I have a start page that gives options to open a login modal or sign up modal. However, once you are in the login modal I give an option so you can switch to sign up modal. However, I can't seem to get this to work. The one time I got it to work, the modal showed up in the wrong section of the screen since it was being opened in relation to the login modal and not the start page.
I am new to React so any insight would be appreciated. Should I use redux, since I can't pass props from child to parent. So that way when I return to start page I can rerender with info saying that I had clicked sign-up link on the login modal.
function LoginContent(props) {
const [ open, setOpen ] = useState(false)
const { show, closeModal } = props;
function handleSubmit(e){
e.preventDefault();
}
function handleSignUpButton(){
closeModal();
console.log(open)
setOpen(!false)
console.log(open)
}
//added so that the component doesn't get affected by parent css
//and is being rendered from the "modal-root" DOM node from the index.html file
return ReactDOM.createPortal(
<>
<div className={show ? "overlay" : "hide"} onClick={closeModal} />
<div className={show ? "modal" : "hide"}>
<button onClick={closeModal} id="close">X</button>
<div className="login_form">
<h1> Log in to Continue </h1>
<form onSubmit={handleSubmit}>
<input className="username" type='text' name='username' placeholder='Email Address' />
<input className="password" type='password' name='password' placeholder='password' />
<button className="login_button"> Sign In</button>
</form>
</div>
<div className="login_demo">
<h3 className="login_demo_pointer" type="submit">Demo Login</h3>
</div>
<hr />
<div className="login_switch">Don't have an account.
<button className="signup_link" onClick={handleSignUpButton}>Sign Up</button>
{open && <SignUpContent open={open} closeModal={closeModal} show={show} />} </div>
</div>
</>, document.getElementById("modal-root")
);
}
function Start() {
const history = useHistory();
const [showLogin, setLogin ] = useState(false);
const openModalLogin = () => setLogin(true);
const closeModalLogin = () => setLogin(false);
const [showSignUp, setShow ] = useState(false);
const openModalSignUp = () => setShow(true);
const closeModalSignUp = () => setShow(false);
return (
<div className="bodyStart">
<img src="https://i.imgur.com/5gjRSmB.gif" alt="" id="bg" />
<div className="start_logo">
<img src={require("../styling/logo.png")} alt="" onClick={() => {
history.push('/home')
history.go(0)}} className="logo" />
</div>
<div className="start">
<div className="start_heading">
<h2>Mother Nature is Calling.</h2>
<h4>Find a place to recharge and escape the day to day.</h4>
</div>
<div className="start_location">
<p>Where?</p>
<div className="start_input">
<input type="text" placeholder="anywhere" />
<ArrowForwardIcon onClick={() => {
history.push('/search')
history.go(0)}}
className="arrow" fontSize="large"/>
</div>
</div>
<div className="start_authentication">
<Button className="login"
variant="contained"
color="primary"
size="large"
onClick={() => openModalLogin()}> Login </Button>
{showLogin && <LoginContent closeModal={closeModalLogin} show={showLogin} />}
<Button className="signup"
variant="contained"
size="large"
onClick={()=> openModalSignUp()}> Sign-Up </Button>
{showSignUp && <SignUpContent closeModal={closeModalSignUp} show={showSignUp} />}
</div>
</div>
</div>
)
}
I have made similar modals with Material-UI. You can change loginOpen state and signupOpen states in modals. See codepen below
Codepen
const { useState } = React;
const { Button, Dialog, DialogTitle, DialogContent, DialogActions } = MaterialUI;
function LoginDialog(props) {
const { open, setLoginOpen, setSignupOpen } = props;
const switchSignup = (event) => {
setLoginOpen(false)
setSignupOpen(true)
}
return (
<Dialog aria-labelledby="simple-dialog-title" open={open}>
<DialogTitle id="simple-dialog-title">LOGIN</DialogTitle>
<DialogContent>If you don't have an account, press SIGNUP</DialogContent>
<DialogActions>
<Button onClick={(event) => {setLoginOpen(false)}}>CLOSE</Button>
<Button>LOGIN</Button>
<Button onClick={switchSignup}>SIGNUP</Button>
</DialogActions>
</Dialog>
);
}
function SignupDialog(props) {
const { open, setLoginOpen, setSignupOpen } = props;
const switchLogin = (event) => {
setSignupOpen(false)
setLoginOpen(true)
}
return (
<Dialog aria-labelledby="simple-dialog-title" open={open}>
<DialogTitle id="simple-dialog-title">SIGNUP</DialogTitle>
<DialogContent>If you have an account, press LOGIN</DialogContent>
<DialogActions>
<Button onClick={(event) => {setSignupOpen(false)}}>CLOSE</Button>
<Button>SIGNUP</Button>
<Button onClick={switchLogin}>LOGIN</Button>
</DialogActions>
</Dialog>
);
}
const App = () => {
const [loginOpen, setLoginOpen] = useState(false)
const [signupOpen, setSignupOpen] = useState(false)
const handleLogin = (event) => {
setLoginOpen(true)
}
const handleSignup = (event) => {
setSignupOpen(true)
}
return (
<div>
<Button variant='contained' color='primary' onClick={handleLogin} >
LOGIN
</Button>
<Button variant='outlined' color='primary' onClick={handleSignup} >
SIGNUP
</Button>
<LoginDialog open={loginOpen} setLoginOpen={setLoginOpen} setSignupOpen={setSignupOpen} />
<SignupDialog open={signupOpen} setLoginOpen={setLoginOpen} setSignupOpen={setSignupOpen} />
</div>
)
}
ReactDOM.render(<App />, document.getElementById("root"));

Hide another component on the click of radio button

I'm very new to React. I'm building a flight booking website. I want to hide the return date form field when the user selects one way trip. I wanted to know what is the best way to go about it.
const TripTypeButton = (props) => {
const [rSelected, setRSelected] = useState(null);
return (
<div>
<ButtonGroup>
<Button color="primary" onClick={() => setRSelected(1)} active={rSelected === 1}>Round Trip</Button>
<Button color="secondary" onClick={() => setRSelected(2)} active={rSelected === 2}>One Way</Button>
</ButtonGroup>
</div>
);
}
const HomePage = (props) =>{
return(
<div>
<div>
<h2> Search for flights</h2>
</div>
<div>
<Form>
<Row form>
<FormGroup>
<TripTypeButton />
</FormGroup>
</Row>
<Row form>
<Col md={3}>
<FormGroup>
<Label>Departure</Label>
<Input type="date" id="departure" name="departure"/>
</FormGroup>
</Col>
<Col md={3}>
<FormGroup>
<Label for="exampleState">Return</Label>
<Input type="date" name="return" id="return"/>
</FormGroup>
</Col>
<Row/>
</Form>
</div>
</div>
);
}
for this situation, you need to keep the state of selected trip type in HomePage component and then based on that state render the Return flight or not!
like below:
const HomePage = (props) => {
const [rSelected, setRSelected] = useState(null);
return (
// some code
// trip type button handler
<TripTypeButton handleSelectedTripType={setRSelected} rSelected={rSelected} />
// the button section of code
{ rSelected !== 1
&& <Col md={3}>
<FormGroup>
<Label for="exampleState">Return</Label>
<Input type="date" name="return" id="return"/>
</FormGroup>
</Col>
}
// rest of jsx code
)
}
and your TripTypeButton would be like below:
const TripTypeButton = ({ handleSelectedTripType, rSelected }) => {
return (
<div>
<ButtonGroup>
<Button color="primary" onClick={() => handleSelectedTripType(1)} active={rSelected === 1}>Round Trip</Button>
<Button color="secondary" onClick={() => handleSelectedTripType(2)} active={rSelected === 2}>One Way</Button>
</ButtonGroup>
</div>
);
}
this is called lifting state up in React! and by that you keep your state in top level components and manage data manipulation by passing required handlers down to the child components by directly props or context!

Changing variable in one file conflicts the data for other file in React JS

I'm having weird problem in React JS. I have two classes named as Notes.js and DataTables.js
I'm using DataTables in Note.js like this
<DataTables
keyField="id"
columns={columns}
url={this.state.url}
useCallBack={true}
onEdit={this.onEdit}
/>
Please Note that DataTables.js is my own custom created DataTable.js not react-datatable.
All the work like fetching data from URL and showing it in tabular form is in DataTables.js file.
Note.js Code:
import React, { Component } from "react";
import { Constant } from "../shared/Constants";
import DataTables from "../shared/DataTables";
import { Modal, Button } from "react-bootstrap";
import BreadCrumb from "../shared/BreadCrumb";
import "../Style.css";
const columns = Constant.notes;
export class Notes extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
url: "notes/get_notes",
showModal: false,
note: [],
};
this.onEdit = this.onEdit.bind(this);
this.onAdd = this.onAdd.bind(this);
this.onUpdate = this.onUpdate.bind(this);
this.saveNote = this.saveNote.bind(this);
}
onUpdate(key, value) {
let noteData = this.state.note;
noteData[key] = value;
this.setState({
note: noteData,
});
}
saveNote(e) {
e.preventDefault();
}
onEdit(n) {
this.setState({
note: n,
showModal: true,
});
}
onAdd() {
this.setState({
note: [],
showModal: true,
});
}
render() {
return (
<>
<Modal
show={this.state.showModal}
aria-labelledby="example-modal-sizes-title-lg"
onHide={() => this.setState({ showModal: false })}
>
<form method="post" onSubmit={this.saveNote}>
<Modal.Header>
<Modal.Title>My Note</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="row">
<div className="col-sm-12">
<div className="form-group">
<label className="text-muted">Note Title</label>
<input
type="text"
placeholder="Note Title"
className="form-control"
ref="title"
value={this.state.note.title}
onChange={(e) => this.onUpdate("title", e.target.value)}
/>
</div>
<div className="form-group">
<label className="text-muted">Content</label>
<textarea
onChange={(e) => this.onUpdate("content", e.target.value)}
className="form-control"
style={{ height: "250px" }}
placeholder="Content"
>
{this.state.note.content}
</textarea>
</div>
</div>
</div>
</Modal.Body>
<Modal.Footer>
<Button
variant="secondary"
onClick={() => this.setState({ showModal: false })}
>
Close
</Button>
<Button type="submit" variant="primary">
Save Note
</Button>
</Modal.Footer>
</form>
</Modal>
<BreadCrumb
title="My Notes"
useCallBack={true}
onAdd={this.onAdd}
active_link="Notes"
link=""
link_text="Add New"
/>
<div className="row">
<div className="col-sm-12">
<div className="card">
<div className="card-body">
<div className="card-title">Notes</div>
<DataTables
keyField="id"
columns={columns}
url={this.state.url}
useCallBack={true}
onEdit={this.onEdit}
/>
</div>
</div>
</div>
</div>
</>
);
}
}
export default Notes;
I'm having Problem in Note.js on onUpdate function
onUpdate(key, value) {
let noteData = this.state.note;
noteData[key] = value;
this.setState({
note: noteData,
});
}
Problem: When I update a field in Modal as you can see in my code, then my Table in DataTable.js automatically gets updated, I'don't why :/
Here is DataTables.js function where I'm sending data to onEdit function
const TableData = () => {
return (
<tbody>
{tableData.length === 0 ?
<tr>
<td className="text-center" colSpan="5"><strong>No Data Found</strong></td>
</tr>
:
tableData.map((tData) => (
<tr key={tData[this.props.keyField]}>
{this.props.columns.map((item, index) => (
<td key={index} className="table-content">
{index === 0 ?
[(useCallback === true ? <span key={"sub_"+index} className="link" onClick={() => this.props.onEdit(tData)}>{tData[item.dataField]}</span> :
<Link
to={
this.props.edit_link +
"/" +
tData[this.props.edit_key_first] + (this.props.edit_key_second ? "/" +
tData[this.props.edit_key_second] : '')
}
>
{tData[item.dataField]}
</Link>
)]
: (
tData[item.dataField]
)}
</td>
))}
</tr>
))}
</tbody>
);
};
Please check gif image below so you can understand it :P
You have an onChange function that is updating the content
onChange={(e) => this.onUpdate("content", e.target.value)}
If you don't want to change the content while typing then you will have to remove this.

Categories

Resources