React - how to invoke popup window in my case? - reactjs

I'm not a React expert yet thus I have a question for you - how to invoke my popup window from:
import {options, columns,convertToArray} from './consts'
const index = () => {
const {data, loading, error, performFetch} = fetchHook({path: "/xxx/yyy", fetchOnMount: true})
return (
<div className={classes.Container}>
<h1>List of products</h1>
<Divider className={classes.Divider} />
<ProductTable data={convertToArray(data)} options={options} columns={columns}/>
</div>
)
}
export default index;
consts.js
export const actions = (productPropertyId, showModal) => {
const productDetails = (productPropertyId) => {
}
const removeProduct = (productPropertyId, showModal) => {
actions(productPropertyId, showModal);
return (
<div className={classes.actionsContainer}>
<Button
onClick={() => productDetails(productPropertyId)}
> {"More"}
</Button>
<Button
const removeProduct = (productPropertyId, showModal) => {
actions(productPropertyId, showModal);
>{"Remove"}
</Button>
</div>
)
};
export const convertToArray = (productList) => {
let products = []
if (productList != null) {
productList.map(product => {
column1, column2, column3, actions(product.id)]
products.push(prod)
})
}
return products;
};
My popup is --> <FormDialog/> based on react Materials.
Is it possible to invoke popup in this place?
I have a react material table with some columns. The last column contains 2 buttons, one of them is "Remove" (row). Here I want to invoke my popup. Maybe I should rebuild my structure?
UPDATE
Below is my popup - I wonder how to run this popup from the place above:
const formDialog = (popupOpen) => {
const [open, setOpen] = React.useState(false);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<div>
{/*<Button variant="outlined" color="primary" onClick={handleClickOpen}>*/}
{/* Open alert dialog*/}
{/*</Button>*/}
<Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title">
<DialogTitle id="form-dialog-title">Subscribe</DialogTitle>
<DialogContent>
<DialogContentText>
To subscribe to this website, please enter your email address here. We will send updates
occasionally.
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="name"
label="Email Address"
type="email"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="primary">
Cancel
</Button>
<Button onClick={handleClose} color="primary">
Subscribe
</Button>
</DialogActions>
</Dialog>
</div>
);
}
export default formDialog;
UPDATE 2
I updated my code taking into cosideration the tips from your response, see above. Can I add a parameter showModal in my export const actions = (productPropertyId, showModal) and then invoke this component with different showModal value? UNfortunately my popup doesn't appear when I click on Remove button :(

You can invoke it conditionally and controle it using some state variable. Like this:
const [removeModal, removeToggle] = useState(false);
return (<>
<div className={classes.actionsContainer}>
<Button
onClick={() => productDetails(productPropertyId)}
> {"More"}
</Button>
<Button
onClick={() => removeToggle(true)}
>{"Remove"}
</Button>
</div>
{removeModal ? <YourComponent /> : ''}
</>
)
I'm using a react fragment there <></> just to position the modal div outside the main div, but you can also invoke it inside your main div as well (I usually do this and set the position: fixed so the modal/popup coud appear in top of everything).

Related

Open a modal (or dialogue) from a dropdown asking the user if they would like to take an action

I would like to open a modal (or dialogue) when a user selects an option from a dropdown menu.
Eventually there will be a few options in the dropdown, and different dialogues/modals will be called and rendered depending on which dropdown option has been clicked. For now - how do I get the modal/dialogue to open with dropdown menu events?
I'm currently using the handleClose handler to attempt to open a dialogue since that event should be easy to grab and use right out of the docs for MUI Menu and MenuItem.
The origination call to the DropdownMenu component (which works well and shows the dropdown menu) occurs in a table through the click of an icon
<DropdownMenu options={['Show modal or dialogue to the user']}>
<MoreHorizIcon />
</DropdownMenu>
The DropdownMenu component (also working well itself, except for not triggering the dialogue/modal) looks like this
interface IProps extends Omit<unknown, 'children'> {
children: any;
options: string[];
}
const ITEM_HEIGHT = 48;
const DropdownMenu = ({ children, options }: IProps) => {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const showModal = () => {
return (
<AlertDialog />
)
}
const handleClose = () => {
//the native alert dialogue works well
alert('I want to show a dialog or modal the same way this alert shows up and ask the user if they are sure they want to delete something')
//why isn't the custom alert dialog being called?
showModal();
setAnchorEl(null);
};
return (
<div>
<IconButton
aria-label="more"
id="more-button"
aria-controls="long-menu"
aria-expanded={open ? 'true' : undefined}
aria-haspopup="true"
onClick={handleClick}
>
{children}
</IconButton>
<Menu
id="dropdownmenu"
MenuListProps={{
'aria-labelledby': 'more-button'
}}
anchorEl={anchorEl}
open={open}
onClose={handleClose}
PaperProps={{
style: {
maxHeight: ITEM_HEIGHT * 4.5,
width: '20ch'
}
}}
>
{options.map(option => (
<MenuItem key={option} onClick={handleClose} >
{option}
</MenuItem>
))}
</Menu>
</div>
);
};
export default DropdownMenu;
And the example starter dialogue I am using to get the ball rolling looks like this
const AlertDialog = () => {
const [open, setOpen] = React.useState(true);
const handleClose = () => {
setOpen(false);
};
return (
<div>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">
{"Sweet Filler Dialog"}
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Are you sure?
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>NO</Button>
<Button onClick={handleClose} autoFocus>
YES
</Button>
</DialogActions>
</Dialog>
</div>
);
}
You can use a state variable to trigger the modal in the DropdownMenu component, whenever you wanted to show the dialog/modal.
const [isModalOpen, setIsModalOpen] = React.useState(false);
and then in the handleClose, you can update the modal state to open the modal.
const handleClose = () => {
setIsModalOpen(true)
setAnchorEl(null);
};
Then somewhere in your JSX of DropdownMenu, you can conditionally render the AlertDialog component like this
{isModalOpen ? <AlertDialog open={isModalOpen} setOpen={setIsModalOpen} /> : null}
Finally, update your AlertDialog component to use props to handle the closing of the modal.
const AlertDialog = ({ open, setOpen }) => {
const handleClose = () => {
setOpen(false);
};
return (
<div>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">
{"Sweet Filler Dialog"}
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Are you sure?
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>NO</Button>
<Button onClick={handleClose} autoFocus>
YES
</Button>
</DialogActions>
</Dialog>
</div>
);
}

Using Form Inside Antd Modal

ERRORCODE:
index.js:1 Warning: Instance created by `useForm` is not connected to any Form element. Forget to pass `form` prop?
I am using React with Antd and I open a modal on a button click, the button passes some data which I am capturing via "e" and render them onto the modal.
The problem is whenever the modal is closed and opened again, the contents inside do not re render, it uses the previous event data. I've figured it is because I am not using the Form properly.
I will post the code below please let me know where I have gone wrong.
import react, antd ...etc
function App () => {
const sendeventdata(e) => {
const EventContent = () => (
<div>
<Form
form={form}
labelAlign="left"
layout="vertical"
initialValues={{
datePicker: moment(event.start),
timeRangePicker: [moment(event.start), moment(event.end)],
}}
>
<Form.Item name="datePicker" label={l.availability.date}>
<DatePicker className="w-100" format={preferredDateFormat} onChange={setValueDate} />
</Form.Item>
<Form.Item name="timeRangePicker" label={l.availability.StartToEnd}>
<TimePicker.RangePicker className="w-100" format="HH:mm" />
</Form.Item>
<span className="d-flex justify-content-end">
<Button
className="ml-1 mr-1"
onClick={() => {
form
.validateFields()
.then((values) => {
onUpdate(values)
form.resetFields()
})
.catch((info) => {
console.log('Validate Failed:', info)
})
}}
>
{l.availability.updateBtn}
</Button>
<Button danger className="ml-1 mr-1" onClick={() => handleDelete()}>
Delete
</Button>
</span>
</Form>
</div>
)
}
const MyModal = () => {
const { title, visible, content } = e
return (
<Modal
onCancel={handleModalClose}
title={title}
visible={visible}
footer={null}
form={form}
destroyOnClose
>
{content}
</Modal>
)
}
return <div><MyModal /><Button onClick{sendeventdata}></Button></div>
}

Material UI Dialog not closing when clicking the overlay

I have created a reusable dialog/modal using React and Material UI.
When I try to click the overlay, something weird happens.
Instead of closing the modal and setting 'open' to false, the scripts directly sets open to true again for some reason.
The handleClickOpen is triggered when clicking the overlay and I can't find the problem causing this.
Dialog component:
const { onClose, open } = props;
const handleClose = () => {
onClose();
};
const preventDef = (e) => {
e.stopPropagation();
};
return (
<Dialog open={open} onClose={onClose} className={className} onClick={handleClose}>
<Container>
<Grid container className={`${className}__container`}>
<Grid item xs={12} sm={props.colsAmount} onClick={preventDef} className={`${className}__column`}>
{props.component}
{props.closeButton && (
<div className={`${className}__close`} onClick={handleClose}>
<Close />
</div>
)}
</Grid>
</Grid>
</Container>
</Dialog>
);
The component I load and trigger the dialog in:
const [open, setOpen] = React.useState(false);
const handleClose = (e) => {
setOpen(false);
};
const handleClickOpen = () => {
setOpen(true);
};
return (
<div className={[classes.ShopCard]} onClick={handleClickOpen}>
<div className={`${classes.ShopCard}__image`}>
<div className={`${classes.ShopCard}__image__wrapper`}>
<img src={image} alt={alt} />
<div className={`${classes.ShopCard}__image__price`}>Vanaf €{price}</div>
</div>
</div>
<div className={`${classes.ShopCard}__content`}>
<Title title={title} size="h6" />
<Body>{description}</Body>
</div>
<div className={`${classes.ShopCard}__button`}>
<Button label="In winkelwagen" startIcon={<AddShoppingCart />} />
</div>
<CustomDialog
open={open}
onClose={handleClose}
colsAmount={6}
component={<ShopPopUp />}
closeButton="true"
/>
</div>
If someone could explain why the open state gets set to true, that would be great.
It's because of:
<div className={[classes.ShopCard]} onClick={handleClickOpen}>
It exists higher up in the DOM than the overlay thus it always fires.

React render not changing when calling from Button

When I click the login or register button in the following react code, the renderView() function is not rendering the Login(or the Register) component on the page.
When I log the value of e.currentTarget.value in the console, the correct values are getting logged when the button is clicked.
How do I fix this?
I want the corresponding components to be displayed when I click the Login or Register Buttons
const AppHomePage = () => {
const classes = useStyles();
const [renderVal, setRenderVal] = useState(0);
const renderView = () => {
switch(renderVal){
case 0:
return <Page />
case 1:
return <Register />
case 2:
return <Login />
default:
return <Page />
}
}
const ButtonChange = (e) => {
setRenderVal(e.currentTarget.value);
}
return(
<div>
<AppBar className={classes.root} position='static' >
<Toolbar className={classes.appbar}>
<Button className={classes.buttons} value={1} variant="contained" color="primary" onClick={ButtonChange}>
Register
</Button>
<Button className={classes.buttons} value={2} variant="contained" color="primary" onClick={ButtonChange}>
Login
</Button>
</Toolbar>
</AppBar>
<div>
{ renderView() }
</div>
<CssBaseline />
</div>
)
}
const Login = () => {
return(
<div>
<p>login</p>
</div>
)
}
const Register = () => {
return(
<div>
register
</div>
)
}
const Page = () => {
return(
<div>
page
</div>
)
}
Pass the value inside onClick function. Use an arrow function and pass the id like 1 or 2. onClick={() => ButtonChange(1)}
<Button className={classes.buttons} variant="contained" color="primary" onClick={() => ButtonChange(1)}>
Register
</Button>
<Button className={classes.buttons} variant="contained" color="primary" onClick={()=>ButtonChange(2)}>
Login
</Button>
Now in ButtonChange function get the value passed in previous step.
const ButtonChange = (id) => {
setRenderVal(id);
}
I fixed it by simply changing the cases from case 1: to case '1': and so on...

Update list item in material ui?

I have a project in react, and I'm building a simple todo app. When an item in the list is clicked, I want to update the value. My code looks like this:
export default function ShowTodos () {
const [todos, setTodos] = React.useState<ITodo[]>([]);
const [selectedTodo, setSelectedTodo] = React.useState<ITodo>({});
const [dialogState, setDialogState] = React.useState<boolean>(false);
const confirm = useConfirm();
useEffect(() => {
getTodos()
.then(({data: {todos}}: ITodo[] | any) => {
const todoList = todos
setTodos(todoList)
})
.catch((err: Error) => console.log(err))
})
const handleConfirmation = (id: string) => {
confirm({ description: 'This action is permanent!' })
.then(() => { deleteTodoById(id).then(r => )})
}
return (
<List>
{todos.map((todo: ITodo ) =>
(
<ListItem onClick={() => {
console.log("hh", todo);
setDialogState(!dialogState)
}
} key={todo._id}>
<ListItemText
primary={todo.text}
/>
<IconButton edge="end" aria-label="delete" onClick={() => handleConfirmation(todo._id)}>
<DeleteIcon />
</IconButton>
<Dialog open={dialogState} aria-labelledby="form-dialog-title">
<DialogTitle id="form-dialog-title">Update</DialogTitle>
<DialogContent>
<TextField
defaultValue={todo.text}
autoFocus
margin="dense"
id="name"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button color="primary" onClick={() => setDialogState(false)}>
Cancel
</Button>
<Button color="primary" onClick={() => updateTodo(selectedTodo)}>
Update
</Button>
</DialogActions>
</Dialog>
</ListItem>
)
)}
</List>
);
}
However the odd thing is that the defaultValue when the item is clicked is always the last item in the list. How am I to change it to be the text of the item clicked?
Thanks!
You need separate state of each todo item to new Component
The main problem in this piece of code:
<ListItem onClick={() => {
console.log("hh", todo);
setDialogState(!dialogState)
}
} key={todo._id}>
onClick you toggling dialog, but not specify selectedTodo.
try something like that:
onClick={() => {
console.log("hh", todo);
setSelectedTodo(todo);
setDialogState(!dialogState);
}
and I guess you should define updateTodo

Resources