React modal window does not show with Hooks - javascript

I'm wondering why my modal view is no showing up. I've followed examples from semantic-ui and also from bootstrap but none are working.
I'm not sure to use Hooks as it requires. Or HandleEditRecipe function is not at top level of my component and it does not render ?
I'd like to display a modal view by clicking on this button:
<button onClick={HandleEditRecipe.bind(null, key, data)}>Edit</button>
This is my code :
import { Modal, Button } from 'react-bootstrap'
const RecipeCard = ({
id: key,
recipies,
updateRecipe,
deleteRecipe,
data
}) => {
const [show, setShow] = React.useState(false)
let recipeUpdate = {
name: '',
image: '',
ingredients: '',
instructions: ''
}
const handleShow = () => setShow(true)
function HandleEditRecipe (key, data) {
const handleClose = () => setShow(false)
return (
<>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className='card'>
<form action='' className='admin-form'>
<input value={data.name} onChange={e => handleChange(e, key)} type='text' name='name' />
<input value={data.image} onChange={e => handleChange(e, key)} type='text' name='image' />
<textarea value={data.ingredients} onChange={e => handleChange(e, key)} name='ingredients' rows='3' />
<textarea value={data.instructions} onChange={e => handleChange(e, key)} name='instructions' rows='15' />
</form>
<button onClick={() => handleValidEdit(key)}>Supprimer</button>
</div>
</Modal.Body>
<Modal.Footer>
<Button variant='secondary' onClick={handleClose}>
Close
</Button>
<Button variant='primary' onClick={handleClose}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</>
)
}
return (
<div className='card'>
<div className='recipe'>
<h2>{data.name} - {key}</h2>
<Button variant='primary' onClick={handleShow}>
Launch demo modal
</Button>
<button onClick={HandleEditRecipe.bind(null, key, data)}>Edit</button>
<div className='image'>
<img src={requireImage(data.image)} alt={data.name} />
</div>
<ul className='list-ingredients'>
{data.ingredients}
</ul>
<ol className='list-instructions'>
{data.instructions}
</ol>
</div>
</div>
)
}
export default RecipeCard
Thank you !
EDIT SOLUTION:
I finally manage to display modal view with hooks :
const RecipeCard = ({
id: key,
recipies,
updateRecipe,
deleteRecipe,
data
}) => {
const [isOpen, setIsOpen] = React.useState(false)
const showModal = () => {
setIsOpen(true)
}
const hideModal = () => {
setIsOpen(false)
}
return (
<div className='card'>
<div className='recette'>
<h2>{data.name} - {key}</h2>
<button onClick={() => handleDeleteRecipe(key)}>Delete</button>
<div className='image'>
<img src={requireImage(data.image)} alt={data.name} />
</div>
<ul className='liste-ingredients'>
{ingredients}
</ul>
<ol className='liste-instructions'>
{instructions}
</ol>
</div>
<button onClick={showModal}>Edit</button>
<Modal show={isOpen} onHide={hideModal}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className='card'>
<h1>DIOOO</h1>
<form action='' className='admin-form'>
<input value={data.name} onChange={e => handleChange(e, key)} type='text' name='name' />
<input value={data.image} onChange={e => handleChange(e, key)} type='text' name='image' />
<textarea value={data.ingredients} onChange={e => handleChange(e, key)} name='ingredients' id='' rows='3' />
<textarea value={data.instructions} onChange={e => handleChange(e, key)} name='instructions' id='' rows='15' />
</form>
</div>
</Modal.Body>
<Modal.Footer>
<button onClick={hideModal}>Close</button>
<button>Save</button>
</Modal.Footer>
</Modal>
</div>
)
}
export default RecipeCard

Related

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).

Modal dialog displays from all elements of mapped array. How to select each item by ts and react js?

This code:
How to display a dialog when a button is clicked using react and typescript?
I wanna open dialog from each todos, how to make it ? I used react js and typescript. Help me to resolve this problem.
interface ListProps {
todos: INote[];
onDelete: (title: string) => void;
}
const TodoList: React.FunctionComponent<ListProps> = ({ todos, onDelete }) => {
const [showAlert, setShowAlert] = useState(false);
const [todo, setTodos] = useState(null);
How to select each item by ts?It doesn't work. What is reason? Thanks!
const handleOpenDialog = (todos: any) => {
setTodos(todos);
setShowAlert(true);
};
const handleCloseDialog = () => {
setShowAlert(false);
};
return (
<>
<section className="list list--wrapper">
{todos.map((todos) => (
<div className="item list__item" key={todos.title}>
<span className="item__title">{todos.title}</span>
<div className="item__group">
<input
className="item__completed"
type="checkbox"
checked={todos.completed}
/>
<span className="item__decs">{todos.desc}</span>
</div>
<div className="item__btn">
<button
className="item__btnd"
onClick={() => handleOpenDialog(todos)}
>
Delete
</button>
<button className="item__btne">Edit</button>
</div>
{showAlert && todo && (
<AlertDialog
handleCloseDialog={handleCloseDialog}
title={todos.title}
/>
)}
</div>
))}
</section>
</>
);
};
export default TodoList;
just add a condition to only show the AlertDialog on selected todos
<section className="list list--wrapper">
{todos.map((todos) => (
<div className="item list__item" key={todos.title}>
<span className="item__title">{todos.title}</span>
<div className="item__group">
<input
className="item__completed"
type="checkbox"
checked={todos.completed}
/>
<span className="item__decs">{todos.desc}</span>
</div>
<div className="item__btn">
<button
className="item__btnd"
onClick={() => handleOpenDialog(todos)}
>
Delete
</button>
<button className="item__btne">Edit</button>
</div>
{showAlert && todos.title===todo?.title && (
<AlertDialog
handleCloseDialog={handleCloseDialog}
title={todos.title}
/>
)}
</div>
))}
</section>
or just move the AlertDialog outside the map
<section className="list list--wrapper">
{todos.map((todos) => (
<div className="item list__item" key={todos.title}>
<span className="item__title">{todos.title}</span>
<div className="item__group">
<input
className="item__completed"
type="checkbox"
checked={todos.completed}
/>
<span className="item__decs">{todos.desc}</span>
</div>
<div className="item__btn">
<button
className="item__btnd"
onClick={() => handleOpenDialog(todos)}
>
Delete
</button>
<button className="item__btne">Edit</button>
</div>
</div>
))}
{showAlert && todo && (
<AlertDialog
handleCloseDialog={handleCloseDialog}
title={todos.title}
/>
)}
</section>

Formik reset button doesn't clear the form

I have the following:
<Formik initialValues={{}} onSubmit={data => console.log(data)}>
<Form className="h-full">
<FieldsWrapper className="hide-scrolling-bar">
{filters?.map(filter => (
<FiltersGroup
name={filter.label}
filters={filter.children}
/>
))}
</FieldsWrapper>
<ButtonsWrapper>
<Button type="submit" text="apply all" isPrimary />
<Button
type="reset"
text="clear all"
isWishList
isPrimary={false}
/>
</ButtonsWrapper>
</Form>
</Formik>
however the reset button doesn't clear the form
FILTERGROUP COMPONENT
...
const FiltersGroup = ({filters, name}) => {
const Checkbox = ({
field: {name, value, onChange, onBlur},
id,
label,
className,
...props
}) => {
return (
<div className="flex">
<input
name={name}
id={id}
type="checkbox"
value={label}
onChange={onChange}
onBlur={onBlur}
className="hidden"
{...props}
/>
<SizeLabel htmlFor={id}>{label}</SizeLabel>
</div>
)
}
return (
<div className="mb-10">
<GroupLabel>{name}</GroupLabel>
<div className="flex flex-wrap">
{filters?.map(filter => (
<Field
component={Checkbox}
name={name}
id={`id-${filter}`}
label={filter}
/>
))}
</div>
</div>
)
}
export default FiltersGroup
Once you have the fields into a Formik tag then:
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
validateOnBlur={false}
validateOnChange={false}
onSubmit={async (values, { resetForm }) => {
await onSubmit(values)
resetForm()
}}
>
....
When you click Submit button it reset automatically
EDIT:
Example:
const initialValues = {
name: ''
}
<Formik
initialValues={initialValues}>
{formik => {
console.log('formik props', formik)
return (
<div>
<h1>EDIT USER</h1>
<Form>
<Field name="name" type="text" />
<br/><br/><br/>
<div>
<button type="reset" onClick={()=>formik.resetForm()}>
Reset All
</button>
</div>
</Form>
</div >
)
}}
</Formik >
In your case:
<Formik initialValues={{}} onSubmit={data => console.log(data)}>
{formik => {
<Form className="h-full">
<FieldsWrapper className="hide-scrolling-bar">
{filters?.map(filter => (
<FiltersGroup
name={filter.label}
filters={filter.children}
/>
))}
</FieldsWrapper>
<ButtonsWrapper>
<Button type="submit" text="apply all" isPrimary />
<Button
type="reset"
text="clear all"
isWishList
isPrimary={false}
onClick={()=>formik.resetForm()}
/>
</ButtonsWrapper>
</Form>
}}
</Formik>

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"));

OnClick Javascript function is not working in React

I have a login page and below shown the jsx of my login page .Login submit button is inside here.on clicking this login button nothin is triggered or no change reflected
import {
Button,
Card,
Form,
Input,
InputGroupAddon,
InputGroupText,
InputGroup,
Container,
Row,
Col,
} from 'reactstrap';
const SectionLogin = ({ onLoginClick, setEmail, setPassword }) => {
return (
<>
<div
className='wrapper'
style={{
backgroundImage: 'url(' + require('app/assets/img/j.jpg') + ')',
}}
>
<Container>
<Row>
<Col
className='mx-auto'
lg='4'
md='6'
style={{ paddingTop: '60px' }}
>
<Card className='card-register' style={{ padding: '15px' }}>
<h3 className='title mx-auto'>Welcome</h3>
<div className='social-line text-center'>
<Button
className='btn-neutral btn-just-icon mt-0'
color='facebook'
// onClick={(e) => e.preventDefault()}
>
<i
className='fab fa-facebook fa-3x'
style={{ color: '#3b5998' }}
/>
</Button>
<Button
className='btn-neutral btn-just-icon mt-0 ml-1'
color='google'
// onClick={(e) => e.preventDefault()}
>
<i
className='fab fa-google-plus fa-3x'
style={{ color: '#db4a39' }}
/>
</Button>
<Button
className='btn-neutral btn-just-icon mt-0 ml-1'
color='twitter'
// onClick={(e) => e.preventDefault()}
>
<i
className='fab fa-twitter fa-3x'
style={{ color: '#00acee' }}
/>
</Button>
</div>
<Form className='register-form'>
<label>Email</label>
<InputGroup className='form-group-no-border'>
<InputGroupAddon addonType='prepend'>
<InputGroupText>
<i className='nc-icon nc-email-85' />
</InputGroupText>
</InputGroupAddon>
<Input
placeholder='Email'
type='email'
// onChange={(e) => setEmail(e.target.value)}
/>
</InputGroup>
<label>Password</label>
<InputGroup className='form-group-no-border'>
<InputGroupAddon addonType='prepend'>
<InputGroupText>
<i className='nc-icon nc-key-25' />
</InputGroupText>
</InputGroupAddon>
<Input
placeholder='Password'
type='password'
// onChange={(e) => setPassword(e.target.value)}
/>
</InputGroup>
<Button
block
className='btn-round'
color='warning'
type='button'
onClick={onLoginClick}
>
Login
</Button>
</Form>
<div className='forgot'>
<Button
className='btn-link'
color='secondary'
// onClick={(e) => e.preventDefault()}
>
Forgot password?
</Button>
</div>
</Card>
<div className='col text-center'>
{/* <Button
className='btn-round'
outline
color='neutral'
href='/register-page'
size='lg'
target='_blank'
>
View Register Page
</Button> */}
</div>
</Col>
</Row>
</Container>
</div>
</>
);
};
export default SectionLogin;
button code is inside this SectionLogin Container(inside return where my login page jsx reside)
import React, { useEffect, useCallback, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import SectionLogin from './LoginPage';
const LoginContainer = () => {
const dispatch = useDispatch();
const onLoginClick = (e) => {
console.log('hereeee');
alert('Hello');
};
return (
<>
<div className='content'>
<SectionLogin
onLoginClick={onLoginClick}
/>
</div>
</>
);
};
export default LoginContainer;
onLoginClick function is not triggering when button is clicked.
Which type of form is Form ? I am gazing redux-form your must therefore have onSubmit handler
import React from 'react'
import { reduxForm, Field } from 'redux-form'
const SectionLogin = ({ onLoginClick, handleSubmit }) => (
<form onSubmit={handleSubmit}>
<div></div>
</form>
)
export default reduxForm({ form: 'formName' })(SectionLogin)

Categories

Resources