I would like to open a modal with a click. The button is visible on my page, but unfortunately the modal does not open when you click it.
Unfortunately I haven't found a solution yet how I can solve the problem.
function ModalPage(props) {
const [username, setUsername] = useState();
const [password, setPassword] = useState();
const [showModal, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<MDBContainer>
<MDBBtn rounded onClick={handleShow}>+</MDBBtn>
<MDBModal show={showModal} onHide={handleClose}>
<MDBModalHeader className="text-center" titleClass="w-100 font-weight-bold">Data Input</MDBModalHeader>
<MDBModalBody>
<form className="mx-3 grey-text">
<MDBInput label="ID" group type="text" validate />
<MDBInput label="Username" group type="email" validate error="wrong" success="right"
onChange={(evt) => setUsername(evt.target.value)}
/>
<MDBInput label="Password" group type="text"
onChange={(evt) => setPassword(evt.target.value)}
/>
<MDBInput type="textarea" rows="2" label="Your message" />
</form>
</MDBModalBody>
<MDBModalFooter className="justify-content-center">
<MDBBtn color="unique" onClick={handleClose}>Send
<MDBIcon far icon="paper-plane" className="ml-2" />
</MDBBtn>
</MDBModalFooter>
</MDBModal>
</MDBContainer>
);
}
export default withRouter(ModalPage);
According to this MDB page, the property used to dictate whether or not a modal is being shown is not show, but rather isOpen. Change
<MDBModal show={showModal} onHide={handleClose}>
To
<MDBModal isOpen={showModal} onHide={handleClose}>
Related
I made a form project with react. My form is working well for now but I want add bootstrap modal to my form.
When I click the enter button, I want to show a modal. I found modal example on the web but I can't establish connection between form and modal. This is my form
import React from "react";
import { useState } from "react";
const Contact = () => {
const [showModal, setShowModal] = useState(false);
const [inputValue, setInputValue] = useState("");
const [emailValue, setEmailValue] = useState("");
const [phoneNumberValue, setPhoneValue] = useState("");
const [countryValue, setCountryValue] = useState("");
const buttonOnClick = () => {
if (inputValue === "" || emailValue === "" || phoneNumberValue === "") {
setShowModal(false)
} else {
setShowModal(true)
setInputValue("")
}
console.log(`Form submitted, ${showModal}`);
}
return (
<div className="main">
<form >
<div className="baslik">
<div className="container center">
<h1>Contact Form</h1>
</div>
</div>
<div className="field" >
<label className="text"> Name And Surname: </label>
<input type="text" className="form" placeholder="Kerem Kurt" required value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
</div>
<div className="field">
<label className="text"> E-mail: </label>
<input type="email" className="form" placeholder="udenditfy#gmail.com" required value={emailValue} onChange={(e) => setEmailValue(e.target.value)} />
</div>
<div className="field">
<label className="text"> Phone Number: </label>
<input type="tel" className="form" pattern="[0-9]*" placeholder="+905373199437" required value={phoneNumberValue} onChange={(e) => setPhoneValue(e.target.value)} />
</div>
<div className="field">
<label className="text" required > Country: </label>
<select className="form" placeholder="Turkiye" required value={countryValue} onChange={(e) => setCountryValue(e.target.value)}>
<option value="Turkiye">Turkiye</option>
<option value="Azerbaijan">Azerbaijan</option>
<option value="Japan">Japan</option>
<option value="Serbia">Serbia</option>
<option value="France">France</option>
</select>
</div>
<button type="button" className="button" onClick={() => buttonOnClick()}> Enter </button>
</form>
</div>
);
};
export default Contact;
And this is modal codes;
import React, { useState } from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
function Example() {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<>
<Button variant="primary" onClick={handleShow}>
Launch static backdrop modal
</Button>
<Modal
show={show}
onHide={handleClose}
backdrop="static"
keyboard={false}
>
<Modal.Header closeButton>
<Modal.Title>Modal title</Modal.Title>
</Modal.Header>
<Modal.Body>
I will not close if you click outside me. Don't even try to press
escape key.
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="primary">Understood</Button>
</Modal.Footer>
</Modal>
</>
);
}
render(<Example />);
If you want to open your modal after the event "click" in your Form component, you have to import the modal in your form.
For example, your Form is in a component called "Form.jsx" and Modal is in "Modal.jsx" :
Inside Form.jsx, you must import your Modal, move the "show" state into your Form.jsx and pass it in Modal props, just like that :
import Modal from '/path/to/Modal.jsx'
const [show, setShow] = useState(false);
<form>
{children}
</form>
<Modal show={show} setShow={setShow}/>
Inside your Modal.jsx, just change a few things :
function Modal(props){
// remove the show State
// Remove the Button with "handleShow" function.
const handleClose = () => props.setShow(false);
<Modal show={props.show}>
<Button onClick={handleClose}>Close</Button>
</Modal>
}
Welcome to world of react development!
Your question is a classic question about sharing state between components. This is what you refer to as "connection" between components.
The solution is generally referred to as "lifting state up". I highly recommend reading through that if you haven't already.
Example:
import React from 'react';
import ReactDOM from 'react-dom/client';
import { useState } from "react";
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
const root = ReactDOM.createRoot(document.getElementById('root'));
const Contact = ({toggleShow}) => {
return (
<div className="main">
<form >
<button type="button" className="button" onClick={() => toggleShow()}> Show Modal </button>
</form>
</div>
);
};
const MyModal = ({show, toggleShow}) => {
return (
<>
<Modal
show={show}
onHide={toggleShow}
backdrop="static"
keyboard={false}
>
<Button variant="secondary" onClick={toggleShow}>
Close
</Button>
</Modal>
</>
);
}
const App = () => {
const [show, setShow] = useState(false);
const toggleShow = () => setShow(!show);
return (
<>
<Contact toggleShow={toggleShow}/>
<MyModal show={show} toggleShow={toggleShow}/>
</>
)
}
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Explanation:
The general idea is to share the show state of the Modal as well as the state toggler toggleShow() between our <Contact> and <MyModal> components.
We can easily achieve this:
create a new parent component <App> (the name is arbitrary) where we define the show state and the toggler function.
pass the state and toggler into the modal: <MyModal state={state} toggleShow={toggleShow} />.
the form only needs the toggler: <Form toggleShow={toggleShow} />
Note that toggleShow can also be split into separate handleShow and handleClose function, but this approach saves us a few lines.
It is a login page component in that I want to open forgot password component. Both components are modal. But when I clicked on Forgot password the login page modal is kept open. I just closed the login pop-up, when I click on it, forgot the password component
Below is the login pop-up component
//Initial state for Modal
const [show, setShow] = useState(false);
//Close Modal
const handleClose = () => {
setShow(false)
};
//On this click Modal get visiblr
const handleShow = () => setShow(true);
<>
<p onClick={handleShow}>LOGIN</p>
//Login Modal
<Modal show={show} onHide={handleClose} className="p-5 authpop">
<Modal.Header closeButton onClick={handleClose}>
<Modal.Title>
Log In
</Modal.Title>
</Modal.Header>
//Form submit
<Form className=" p-3" onSubmit={handleSubmit}>
<Form.Group className="mb-3 validateInput">
<Form.Label>Enter email id</Form.Label>
<Form.Control ref={emailRef} className="inputField" id="loginEmail" type="email" placeholder="Your email"
onChange={validateEmail}
/>
<span className="errorMsg" >{emailError}</span>
</Form.Group>
<Form.Group className="mb-3 validateInput">
<Form.Label>Enter Password</Form.Label>
<Form.Control ref={passwRef} className="inputField" id="loginPass" type="password" placeholder="Password"
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Group>
<Form.Group className="mb-3 d-flex justify-content-center">
<Button className="SelectLogBtns LoginBtns" variant="primary" type="Submit">
Log In
</Button>
</Form.Group>
<div className="errorMsg d-flex mb-3" >{error}</div>
<Form.Group className="mb-3 loginlsRw">
<div className="forgottLink eqSpace justify-content-start">
//ForgottPassword Component link
<ForgottPassw/>
</div>
</Form>
</Modal>
</>
//Here is forgot password component
`const ForgottPassw = () => {
const [Fogshow, setFogShow] = useState(false);
const [showBtn, setShowBtn] = useState(false);
const handleFogClose = () => setFogShow(false);
const handleFogShow = () => setFogShow(true);
const { forgottPass } = useUserAuth();
return (
<> <p onClick={handleFogShow}>Forgott Password</p>
<Modal show={Fogshow} onHide={handleFogClose} className="p-5 authpop">
<Modal.Header closeButton onClick={handleFogClose}>
</Modal.Header>
<Form className="p-3" onSubmit={handleForgott}>
<Form.Group className="mb-3 validateInput">
<Form.Label>Enter email id</Form.Label>
<Form.Control ref={emailRef} className="inputField" id="loginEmail" type="email" placeholder="Your email"
onChange={validateFogEmail}
/>
<span className="errorMsg" >{emailError}</span>
</Form.Group>
//Reset Link
<Form.Group style={{ visibility: showBtn ? 'visible' : 'hidden' }} className="mb-3 d-flex justify-content-center">
Send Reset Link
</Form.Group>
</>
);
}`
Well, the login modal isn't gonna go anywhere unless you make it that way. At the moment the login modal is rendered when the show state is true. Even if you click the forget-password link, it will stay open because you aren't reverting the state to false. Wherever is the logic to make the forget modal visible, include setShow(false) for login modal. Because I can't say what you are doing in your ForgetPassword file and your main component, I can't say much.
I know this is a simple workaround you can do other things to make it work, but simply you can just pass both show and setShow as props to the to the forget-password component like this.
<ForgottPassw show={show} setShow={setShow} />
and then in your functional component, you can take the props and change the handleFogShow function to this
const ForgottPassw = ({show, setShow}) => {
//...
const handleFogShow = () => {
setShow(false);
setFogShow(true);
}
}
let me know if it fix the issue.
I am working on a web project using reactjs and I faced some problems exactly 2.
The first one is when I want to send a request to my api using axios.
This is what I have done so far:
import auction1 from '../../Images/auction1.png'
import {useState} from 'react';
import './HomeScreen.css'
import {Button, Modal } from 'react-bootstrap';
import axios from 'axios';
const HomeScreen = ()=>{
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const [img, setImg] = useState("");
const [name, setName] = useState("");
const [price, setPrice] = useState(null);
const [deadline, setDeadLine] = useState("");
const [description, setDescription] = useState("");
const [message, setMessage] = useState(null);
const [error, setError] = useState(false);
const handleSubmit = async(e)=>{
e.preventDefault();
try{
const config = {
headers: {
"Content-Type": "application/json",
},
};
const {data} = await axios.post("http://localhost:7500/api/users/posts"
,{name, img, deadline, price, description},config);
console.log(data);
}catch{
setError(error.response.data.message);
}
};
return(
<div className="container bg">
<img src ={auction1} className='landing-image' />
<div style={{marginLeft:460}}>
<Button variant="primary" onClick={handleShow}>
Create Post
</Button>
</div>
<Modal show={show} onHide={handleClose}>
<form onSubmit={handleSubmit}>
<Modal.Header closeButton>
<Modal.Title>Create Post</Modal.Title>
</Modal.Header>
<Modal.Body>
<form >
<div className="form-group">
<label>Post Name:</label>
<input type="text" className="form-control" placeholder="Enter Name"
value={name} onChange={(e)=> setName(e.target.value)}/>
</div>
<div className="form-group">
<label>Post Images:</label>
<input type="file" className="form-control" multiple onChange="readURL(this)" accept="Image/*"
value={img} onChange={(e)=> setImg(e.target.value)}/>
</div>
<div>
<label>Price:</label>
<input type="number" className="form-control" placeholder="TND"
value={price} onChange={(e)=> setPrice(e.target.value)}/>
</div>
<div>
<label>DeadLine:</label>
<input type="date" className="form-control"
value={deadline} onChange={(e)=> setDeadLine(e.target.value)}/>
</div>
<div>
<label>Description:</label>
<textarea className="form-control" rows="3"
value={description} onChange={(e)=> setDescription(e.target.value)}/>
</div>
</form>
</Modal.Body>
<Modal.Footer>
<button type="submit" className="btn btn-primary" data-bs-dismiss="modal" onClick={handleClose} >
Save Post
</button>
<button type="submit" className="btn btn-secondary" data-bs-dismiss="modal" onClick={handleClose}>
Close
</button>
</Modal.Footer>
</form>
</Modal>
</div>
)
};
export default HomeScreen;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
The Piece of code above is my Home Component in which I have a popup form that shows up when I click on create post button then after filling the form I am getting this error on the console:
The error I had
And a last thing even with unsuccessful submit when I click on the create button again to refill the form I get this type of error:
The second error I had
I would be so grateful if you give a hand on this.
When I press enter key I get this error: Form submission canceled because form is not connected. But Add User button work right.
function Form({ modal, showModal, onAddUser }) {
const [name, setName] = useState('');
const [surname, setSurname] = useState('');
const [age, setAge] = useState('');
const createUser = (e) => {
if (!name || !age || !surname) {
return;
} else {
onAddUser(name, age, surname)
console.log(name, age)
}
setName('');
setAge('')
setSurname('');
showModal(false)
console.log(e);
}
return (
<>
{modal ? <FormContainer onSubmit={createUser}>
<InputContainer value={name} onChange={(e) => setName(e.target.value)} type="text" placeholder="Enter name" />
<InputContainer value={age} onChange={(e) => setAge(e.target.value)} type="number" placeholder="Enter age" />
<InputContainer value={surname} onChange={(e) => setSurname(e.target.value)} type="text" placeholder="Enter surname" />
<Button style={{ marginRight: "10px" }} type="cancel" onClick={() => showModal(false)}>Cancel</Button>
<Button type="button">Add User</Button>
</FormContainer>
: (null)
}
</ >
)
}
You should change the "Add User" button type to submit instead of button.
Also, you should call e.preventDefault() on the form submission.
Your component should be like this,
function Form({ modal, showModal, onAddUser }) {
const [name, setName] = useState('');
const [surname, setSurname] = useState('');
const [age, setAge] = useState('');
const createUser = (e) => {
// add this line here to prevent `form` element default behaviour
e.preventDefault();
if (!name || !age || !surname) {
return;
} else {
onAddUser(name, age, surname)
console.log(name, age)
}
setName('');
setAge('')
setSurname('');
showModal(false)
console.log(e);
}
return (
<>
{modal ? <FormContainer onSubmit={createUser}>
<InputContainer value={name} onChange={(e) => setName(e.target.value)} type="text" placeholder="Enter name" />
<InputContainer value={age} onChange={(e) => setAge(e.target.value)} type="number" placeholder="Enter age" />
<InputContainer value={surname} onChange={(e) => setSurname(e.target.value)} type="text" placeholder="Enter surname" />
<Button style={{ marginRight: "10px" }} type="cancel" onClick={() => showModal(false)}>Cancel</Button>
{/* here we changed type="button" to type="submit" */}
<Button type="submit">Add User</Button>
</FormContainer>
: (null)
}
</ >
)
}
I am trying to open ANTD modal when i click on button on the form using the below code
This is HTML code:
<div>
<Button type="primary" size={buttonsize.size} onClick={createproject1}>
Add New Project
</Button>
<div>
<div>
<Modal
title="Add New project"
visible={setvisible.visible}
onOk={handleOk}
onCancel={handleCancel}
>
<Input size="small" placeholder="Project Name" onChange={handleChange('projectName')} />
<br />
<br />
<Input size="small" placeholder="Project Number" onChange={handleChange('projectNumber')} />
<br />
<br />
<Input size="small" placeholder="Area" onChange={handleChange('area')} />
<br />
<br />
</Modal>
</div>
This is the hook and other state stuff:
const [visible, setvisible] = useState({ visible: false });
const createproject1 = (e) => {
setvisible.visible = true;
};
I am not sure where i am going in wrong direction.. could any one please let me know is there any way to open a modal that would be very grateful to me
From the docs:
Returns a stateful value, and a function to update it.
setvisible is a function, which allows you to update the state. You would need to call it like so:
setvisible({visible: true});
Since this is as simple as a bool, and object isn't necessary here:
const [visible, setVisible] = useState(false)
Then you could simply call:
setVisible(true);
Since you're still having issues, let me make this dirt simple for you:
const [visible, setVisible] = useState(false)
And your component:
<div>
<Button type="primary" size={buttonsize.size} onClick={() => setVisible(true)}>
Add New Project
</Button>
<div>
<div>
<Modal
title="Add New project"
visible={visible}
onOk={handleOk}
onCancel={handleCancel}
>
<Input size="small" placeholder="Project Name" onChange={handleChange('projectName')} />
<br />
<br />
<Input size="small" placeholder="Project Number" onChange={handleChange('projectNumber')} />
<br />
<br />
<Input size="small" placeholder="Area" onChange={handleChange('area')} />
<br />
<br />
</Modal>
</div>
For creating hooks as single value variable, you don't have to create hooks like this..
const [visible, setvisible] = useState({ visible: false });
Instead use this...
const [visible, setvisible] = useState(false);
Here setVisible is Hooks function not an object..
So you cannot set visible value by setVisible.visible = true.
Rather you should have you write this :
setVisible(true)
and Use visible variable as visible attribute of modal .
<Modal
...
visible={visible}
...
>