I have a react modal, which inside a body contains a button, on clicking this button it opens new page eg payment page but the modal still open, now I want on the click it should open a new page and close the modal.
Here is my modal
function ModalA() {
const history = useHistory();
const dispatch = useDispatch();
const handleCloseModal = () => {
dispatch(actions.modalsActions.closeModal({
id: "ModalA",
}))
}
return (
<Modal id="ModalA">
<button onClick={}>Upgrade Now</button>
</Modal>
)
}
export default ModalA
Now when I click the Upgrade now button it open a new page but it does not close the modal.
Is there any good solution for this problem?
You just have to call both functions inside the onClick. The below code should work
<button onClick={() =>{
handleCloseModal()
history.push('/account/payments')
}}>Upgrade Now</button>
Related
I have an item and when I click on more info button a modal window with description appears but there is no endpoint like /modal in current route cause it's not external page I redirect to.
So in my modal window I have make a bid button and I can set a price in case I'm logged in.
otherwise Modal window with login form should appear with a request to log in.
This modal is on my navBar that is fixed whether I'm on current page or another one.
So how to pass this Modal Log in using function from another component ?
Here is my Modal with item description:
const ModalDetails = (props) => {
console.log(props, ' for modal')
const [loggedIn, setLoggedIn] = useState(false)
const checkUser = () => {
if (!loggedIn) {
/// how to pass that path to log in modal??
}
}
return (
{ item.typeSale == 'auction' && <button className='btn-item auction-btn-bet'
onClick={checkUser}>Make a bet</button>}
)
}
Log in modal in my App.js
const App = () => {
...
<Nav.Link className=' nav-item link-nav button-nav' onClick={handleShow}>
<img className='img-small' src={person} />
Log in
</Nav.Link>
<LoginForm show={show} handleShow={handleShow} handleClose={handleClose} />
}
I have everything as a separate component
I don't think it is possible. I think you can use Redux or Context to store the modal's open state.
I use react in the project. The modal closes when the user refreshes, but I want to modify it so that it doesn't close. I found 'beforeunload' event, but I want to prevent 'alert' from appearing.
And when I refresh, I want to keep the data I received from the API and maintain the model.
I want to make the modal close only when I press the close button, what methods can I use?
This is not a real code. Just a example...
function Modal() {
const [open, setOpen] = useState(false)
const handleOpen = () => {
setOpen(!open);
}
return (
<Modal>
<button onClick={handleOpen}>
modal
</button>
(some data from API)
</Modal>
)
}
Read localStorage value first, if it exists use it, and then everytime you set a new value update it in local storage as well.
Remember localstorage only saves values as a string; and when it doesn't exist it will come back as a null.
function Modal() {
const [open, setOpen] = useState(JSON.parse(localStorage.getItem("open")) || false)
const handleOpen = () => {
setOpen((prevState) => {
localStorage.setItem("open", !prevState);
return !prevState;
});
}
return (
<Modal>
<button onClick={handleOpen}>
modal
</button>
</Modal>
)
}
I want to close the dialog by clicking a button using TypeScript and React.
What I am trying to do:
On [click me] button click, isDialogOpen state is set to true and dialog shows up if isDialogOpen is true.
This dialog should close if this [click me] button is clicked or user clicks anywhere outside the dialog.
Below is my code:
function Parent() {
const [isDialogOpen, setIsDialogOpen] = React.useState(false);
return (
<button onClick={() => setIsDialogOpen(!isDialogOpen)}> click me </button> //on clicking this
//button should open the dialog. if dialog open
//and clicking this button again should close the dialog
{isDialogOpen &&
<Dialog setIsDialogOpen={setIsDialogOpen}/>
}
);
}
function Dialog({setIsDialogOpen}: Props) {
const dialogRef = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
const handleClickOutsideDialog = (event: any) => {
if (
dialogRef && dialogRef.current &&
!dialogRef.current.contains(event.target)
) {
setIsDialogOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutsideDialog);
return () => {
document.removeEventListener('mousedown', handleClickOutsideDialog);
};
}, [setIsDialogOpen, dialogRef]);
return (
<Wrapper ref={dialogRef}>
<Title> title </Title>
<Description> some big description </Description>
</Wrapper>
);
}
It works fine. But the problem is once the dialog is opened then clicking the click me button....the dialog disappears and immediately opens.
I am expecting the dialog to close when the user clicks click me button if the dialog is opened before.
I don't know where the problem is. Could someone help me with this? Thanks.
EDIT
below is what i have tried again adding a ref to button click me. and passing it to dialog component to check in useeffect method.
function Parent() {
const [isDialogOpen, setIsDialogOpen] = React.useState(false);
const buttonRef = React.useRef<HTMLDivElement>(null);
const handleClick = () => {
if (!isDialogOpen) {
setIsDialogOpen(true);
}
};
return (
<button onClick={handelClick}> click me </button> //on clicking this
//button should open the dialog. if dialog open
//and clicking this button again should close the dialog
{isDialogOpen &&
<Dialog setIsDialogOpen={setIsDialogOpen} buttonRef={buttonRef}/>
}
);
}
function Dialog({setIsDialogOpen, buttonRef}: Props) {
const dialogRef = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
const handleClickOutsideDialog = (event: any) => {
if (
dialogRef && dialogRef.current &&
!dialogRef.current.contains(event.target) && buttonRef &&
buttonRef.current && !buttonRef.current.contains(event.target)
) {
setIsDialogOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutsideDialog);
return () => {
document.removeEventListener('mousedown', handleClickOutsideDialog);
};
}, [setIsDialogOpen, dialogRef]);
return (
<Wrapper ref={dialogRef}>
<Title> title </Title>
<Description> some big description </Description>
</Wrapper>
);
}
but this keep the dialog open even though user clicks the click me button. clicking outside the dialog will close it.
Continued from comments.
Try setIsDialogOpen((open) => !open)
You have a race condition. For appearance sake, you could use const onClickClickMe = () => { if (!isDialogOpen) setIsDialogOpen(true) }; Then set onClick={onClickClickMe}
Why not to just pass the isDialogOpen state to your Dialog and handle the toggle (show and hide of dialog) according to that? Something like:
function Parent() {
const [isDialogOpen, setIsDialogOpen] = React.useState(false)
const ToggleState = setIsDialogOpen(!isDialogOpen)
return (
<>
<button onClick={ToggleState}>Click me</button>
<Dialog isOpen={isDialogOpen} />
</>
);
}
So, I have re-used a login/register modal and added a Modal to be able to show/hide it.
So I have implementend in the index.js below:
const Form = ({ initialState = STATE_SIGN_UP, showPopUp = STATE_HIDE }) => {
const [mode, toggleMode] = useToggle(initialState);
const [display, toggleDisplay] = useToggleDisplay(showPopUp);
return (
<Modal className="modal" show={showPopUp} size="lg">
<Container pose={mode === STATE_LOG_IN ? "signup" : "login"}>
<div className="container__form container__form--one">
<FormLogin mode={mode} />
</div>
<div className="container__form container__form--two">
<FormSignup mode={mode} />
</div>
<Overlay toggleMode={toggleMode} mode={mode} />
</Container>
</Modal>
);
};
and I have added in FormLogin a close icon and added onClick. I used a console.log to verify if it's working. However, I do not understand how to be able to send and make the modal in the index.js closed when the action on close happened in the FormLogin class.
I tried to use the toggleDisplay but I have lost my track doing it. toogleDisplay is done as below:
export const STATE_SHOW = true
export const STATE_HIDE = false
const useToggleDisplay = initialState => {
const [display, setDisplay] = useState(initialState)
const toggleDisplay = () =>
setDisplay(display === STATE_SHOW ? STATE_HIDE : STATE_SHOW)
return [display, toggleDisplay]
}
export default useToggleDisplay
Any idea ?
Just pass an onClose handler(which equals toggleMode here) to your modal and call it every time the close button is clicked.
You need to call toggleDisplay in order to close your modal, pass it into your form component
<FormLogin mode={mode} toggleDisplay={toggleDisplay} />
Then inside FormLogin component wherever your click handler is for closing the modal pass in toggleDisplay(false)
<button onClick={() => toggleDisplay(false)}>Close</button>
I am using the React native popup dialog package. I'm trying to close the dialog onPress and then navigate away from the screen. The navigation is happening, but the dialog remains open. And a warning Can't perform a react state update on an unmounted component is shown.
<Dialog
dialogStyle = {{textAlign:'center'}}
visible={this.state.dialogVisible}
height = {150}
dialogAnimation={new SlideAnimation({
slideFrom: 'bottom',
})}
>
<DialogTitle
title = {"Information"}
textStyle = {{textAlign:'center',fontFamily:'raleway-regular',color:'#4abce3'}}
/>
<DialogContent style = {{justifyContent:'center',alignContent:'center'}}>
<Text>{this.state.requestResult}</Text>
<Button
title = "Okay!"
onPress = {()=>{ this.navigate() }}
type = "outline"
buttonStyle = {styles.dialogButton}
titleStyle = {styles.choiceButtonTitle}
/>
</DialogContent>
</Dialog>
The navigate()function
navigate = () => {
const { navigation } = this.props;
this.setState({dialogVisible:false})
navigation.navigate('Home');
}
setState is async, which does not block the execution. When setState gets called next line executes (setState is yet to complete) and you got navigated to Home.
You can you callback in setState for navigation.
navigate = () => {
const { navigation } = this.props;
this.setState({dialogVisible:false}, () => navigation.navigate('Home'))
}