Multiple Modal Opening when Updating a Row using React - javascript

I created a project using React and Bootstrap Table. Opening of modal is functional but unfortunately all the data in the table also opens their own modal.
So example I have 5 data in the table, when updating a row, the other four (4) modal also rendered and display.
The id of the data from Firestore is accessible to the child component (Edit_Modal.tsx) is there a way to add an id for the modal to make a reference to the data?
Manuscript.jsx
<tbody>
{thesisData.map((doc, index) => {
return (
<tr key={doc.id}>
<td>{index + 1}</td>
<td>{doc.title}</td>
<td>
{doc.members[0]}, {doc?.members[1]}
</td>
<td>{doc.adviser}</td>
<td>{doc.course}</td>
<td>{doc.pages}</td>
<td className="m-1 text-center">
<Button
className="mb-1"
variant="secondary"
onClick={(e) => openUpdateModal(doc.id, e)}
>
<IconContext.Provider value={{ color: "#fff" }}>
<div>
<BsFillPencilFill />
</div>
</IconContext.Provider>
{showModalEdit && <Edit_Modal modalToggle={doc.id} />}
</Button>
<Button
className="mb-1"
variant="danger"
onClick={(e) => deleteHandler(doc.id)}
>
<IconContext.Provider value={{ color: "#fff" }}>
<div>
<BsFillTrashFill />
</div>
</IconContext.Provider>
</Button>
</td>
</tr>
);
})}
</tbody>
openUpdateModal() function
const openUpdateModal = (id) => {
setThesisId(id);
setShowModalEdit(true);
};
Edit_Modal.tsx
const Edit_Modal = ({ modalToggle }) => {
//Use States for Modal
const [show, setShow] = useState(true);
const handleClose = () => {
setShow(!show);
};
return ReactDom.createPortal(
<div>
<Modal
show={show}
keyboard={false}
onHide={handleClose}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
Update Thesis Details
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form
noValidate
validated={validated}
id="addFormId"
onSubmit={handleUpdateForm}
>
<Row className="mb-3">
<Form.Group as={Col} controlId="formGridTitle">
<Form.Label>Title</Form.Label>
<Form.Control
type="text"
onChange={(e) => setTitle(e.target.value)}
placeholder="Enter title"
value={title}
required
/>
<Form.Control.Feedback type="invalid">
Please enter a title.
</Form.Control.Feedback>
</Form.Group>
<Form.Group as={Col} controlId="formGridAdviser">
<Form.Label>Adviser</Form.Label>
<Form.Control
type="text"
onChange={(e) => setAdviser(e.target.value)}
placeholder="Name of Adviser"
value={adviser}
required
/>
<Form.Control.Feedback type="invalid">
Please enter an Adviser.
</Form.Control.Feedback>
</Form.Group>
</Row>
<Form.Group className="mb-3" controlId="formGridAbstract">
<Form.Label>Abstract</Form.Label>
<Form.Control
as="textarea"
onChange={(e) => setAbstract(e.target.value)}
rows={3}
placeholder="Enter Abstract Details"
value={abstract}
required
/>
<Form.Control.Feedback type="invalid">
Please enter Abstract Details.
</Form.Control.Feedback>
</Form.Group>
<Button type="Submit">Add Content</Button>
</Form>
</Modal.Body>
</Modal>
</div>,
document.getElementById("modal-root")
);
};
export default Edit_Modal;

As #adhinarayan said you can use the useState of setThesisId to get the specific ID of your document.
Example useState:
const [thesisId, setThesisId] = useState("");
You can use the openUpdateModal function to get the Modal and the thesis ID
const openUpdateModal = (id) => {
setThesisId(id); //useState for ID
setShowModalEdit(true); //useState for Modal
};
Finally, make sure that the Modal Component was placed outside of the map function to avoid looping of modals. You can set the thesisId to customized props of Edit_Modal
...</tbody>
</Table>
{showModalEdit && <Edit_Modal modalToggle={thesisId} />}
</Col>...

Related

I am trying to open one modal from another modal in React.js. but previous modal kept open

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.

How to make modal appear onClick change?

I am stuck on getting my Modal to appear when the Edit button is clicked. I can see that the modalShow is being set to true when I click the button since I console.log the value. Any idea on how to get modal to appear when user clicks the edit button?
product-screen.jsx
import { useState } from 'react';
import { Button, Card, Form, Modal } from 'react-bootstrap';
import 'reactjs-popup/dist/index.css';
import ModalScreen from './modal-screen';
const ProductCardScreen = ({ product }) => {
const { productName, productPrice, productInStock, productDescription } =
product;
const [modalShow, setModalShow] = useState(false);
const [updateProduct, setProductUpdate] = useState({
productDescription,
productInStock,
productName,
productPrice,
});
const handleChange = (event) => {
console.log('event', event.target.value);
setProductUpdate({
...updateProduct,
[event.target.name]: event.target.value,
});
};
// todo
const saveUpdatedProduct = (product) => {
// save logic here to db
};
const handleDelete = () => {
alert('Are you sure you want to delete?');
};
const handleModalChange = () => {
console.log('called');
setModalShow(true);
};
return (
<div>
<Card>
<Card.Body>
<Card.Title>Product Name: {product.productName}</Card.Title>
<Card.Text>
Product Description: {product.productDescription}
</Card.Text>
<Card.Text>Product Quantity: {product.productInStock}</Card.Text>
<Card.Text>Price: ${product.productPrice}</Card.Text>
<div
style={{
float: 'right',
}}
>
<Button
style={{ margin: '10px' }}
onClick={() => handleModalChange()}
className='btn btn-primary'
variant='primary'
>
Edit
</Button>
<Button
onClick={() => handleDelete()}
className='btn btn-danger'
variant='primary'
>
Delete
</Button>
</div>
</Card.Body>
</Card>
<ModalScreen product={product} handleChange={handleChange} />
</div>
);
};
export default ProductCardScreen;
modal-screen.jsx
import { Button, Form, Modal } from 'react-bootstrap';
const ModalScreen = ({ product, handleChange }) => {
const { productName, productPrice, productInStock, productDescription } =
product;
return (
<Modal
animation={false}
size='lg'
aria-labelledby='contained-modal-title-vcenter'
centered
>
<Modal.Header>
<Modal.Title id='contained-modal-title-vcenter'>
Product Information
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form>
<Form.Group className='mb-3'>
<Form.Label>Name</Form.Label>
<Form.Control
onChange={handleChange}
value={productName}
type='text'
/>
</Form.Group>
<Form.Group className='mb-3'>
<Form.Label>Description</Form.Label>
<Form.Control
onChange={handleChange}
value={productDescription}
type='text'
/>
</Form.Group>
<Form.Group className='mb-3'>
<Form.Label>Amount In Stock</Form.Label>
<Form.Control
onChange={handleChange}
value={productInStock}
type='text'
/>
</Form.Group>
<Form.Group className='mb-3'>
<Form.Label>Price</Form.Label>
<Form.Control
onChange={handleChange}
value={`$${productPrice}`}
type='text'
/>
</Form.Group>
<Button variant='primary' type='button'>
Save
</Button>
<Button variant='danger' type='button'>
Cancel
</Button>
</Form>
</Modal.Body>
<Modal.Footer></Modal.Footer>
</Modal>
);
};
export default ModalScreen;

Binding input type using refs in reactjs

I am a beginner in reactJS and would like to ask a simple question. I am following some tutorials and I really don't know why this wont work on mine. I know my question is very simple since I am a beginner. Please have a patience with my question.
I have this code from a function component form:
function Login() {
const emailInputRef = useRef();
const passwordInputRef = useRef();
function submitHandler(e) {
e.preventDefault();
const emailInput = emailInputRef.current.value;
const passwordInput = passwordInputRef.current.value;
console.log(emailInput);
}
return (
<>
<Col lg="5" md="7">
<Card className="bg-secondary shadow border-0">
<CardBody className="px-lg-5 py-lg-5">
<div className="text-center text-muted mb-4">
<small>Sign in</small>
</div>
<Form role="form" onSubmit={submitHandler}>
<FormGroup className="mb-3">
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-email-83" />
</InputGroupText>
</InputGroupAddon>
<Input
placeholder="Email"
type="email"
autoComplete="new-email"
ref={emailInputRef}
/>
</InputGroup>
</FormGroup>
<FormGroup>
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-lock-circle-open" />
</InputGroupText>
</InputGroupAddon>
<Input
placeholder="Password"
type="password"
autoComplete="new-password"
ref={passwordInputRef}
/>
</InputGroup>
</FormGroup>
<div className="custom-control custom-control-alternative custom-checkbox">
<input
className="custom-control-input"
id=" customCheckLogin"
type="checkbox"
/>
<label
className="custom-control-label"
htmlFor=" customCheckLogin"
>
<span className="text-muted">Remember me</span>
</label>
</div>
<div className="text-center">
<Button className="my-4" color="primary" type="submit">
Sign in
</Button>
</div>
</Form>
</CardBody>
</Card>
<Row className="mt-3">
<Col xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Forgot password?</small>
</a>
</Col>
<Col className="text-right" xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Create new account</small>
</a>
</Col>
</Row>
</Col>
</>
);
}
I want to bind my input type from my submitHandler and log the values of the input types. I followed a tutorial using refs and I don't know if I made something wrong about it since I was a beginner. When I logged the values it gives me undefined values.
To get the current input reference use innerRef property instead of ref:
<Input
placeholder="Email"
type="email"
autoComplete="new-email"
innerRef={emailInputRef}
/>
const emailInput = emailInputRef.current.value;
ref will only get you a reference to the Input component, innerRef will get you a reference to the DOM input.
You have a few options for that. You can use the useRef React hook or the state stored using the useState React Hook. In both cases you need to import the related hook first. You could use both if you want. You could also use a custom hook with the useReducer React hook.
In your case it would be something like these:
Option # 1: Using useRef
import {useRef} from "react";
function Login() {
const emailInputRef = useRef();
const passwordInputRef = useRef();
function submitFormHandler(event) {
event.preventDefault();
const email = emailInputRef.current.value;
const password = passwordInputRef.current.value;
console.log(`email = ${email} & password = ${password}`);
}
return (
<>
<Col lg="5" md="7">
<Card className="bg-secondary shadow border-0">
<CardBody className="px-lg-5 py-lg-5">
<div className="text-center text-muted mb-4">
<small>Sign in</small>
</div>
<Form role="form" onSubmit={submitFormHandler}>
<FormGroup className="mb-3">
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-email-83"/>
</InputGroupText>
</InputGroupAddon>
<Input
placeholder="Email"
type="email"
id='email'
name='email'
required
autoComplete="new-email"
ref={emailInputRef}
/>
</InputGroup>
</FormGroup>
<FormGroup>
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-lock-circle-open"/>
</InputGroupText>
</InputGroupAddon>
<input
placeholder="Password"
type="password"
id="password"
name="password"
required
autoComplete="new-password"
ref={passwordInputRef}
/>
</InputGroup>
</FormGroup>
<div className="custom-control custom-control-alternative custom-checkbox">
<input
className="custom-control-input"
id=" customCheckLogin"
type="checkbox"
/>
<label
className="custom-control-label"
htmlFor=" customCheckLogin"
>
<span className="text-muted">Remember me</span>
</label>
</div>
<div className="text-center">
<Button className="my-4" color="primary" type="submit">
Sign in
</Button>
</div>
</Form>
</CardBody>
</Card>
<Row className="mt-3">
<Col xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Forgot password?</small>
</a>
</Col>
<Col className="text-right" xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Create new account</small>
</a>
</Col>
</Row>
</Col>
</>
);
};
export default Login;
Option # 2: Using useState
import {useState} from "react";
function Login() {
const [emailState, setEmailState] = useState('');
const [passwordState, setPasswordState] = useState('');
function submitFormHandler(event) {
event.preventDefault();
console.log(`email = ${emailState} & password = ${passwordState}`);
}
const onEmailChangeHandler = (event) => {
setEmailState(event.current.value);
};
const onPasswordChangeHandler = (event) => {
setPasswordState(event.current.value);
};
return (
<>
<Col lg="5" md="7">
<Card className="bg-secondary shadow border-0">
<CardBody className="px-lg-5 py-lg-5">
<div className="text-center text-muted mb-4">
<small>Sign in</small>
</div>
<Form role="form" onSubmit={submitFormHandler}>
<FormGroup className="mb-3">
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-email-83"/>
</InputGroupText>
</InputGroupAddon>
<input
placeholder="Email"
type="email"
id='email'
name='email'
required
autoComplete="new-email"
value={emailState}
onChange={onEmailChangeHandler}
/>
</InputGroup>
</FormGroup>
<FormGroup>
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-lock-circle-open"/>
</InputGroupText>
</InputGroupAddon>
<input
placeholder="Password"
type="password"
id="password"
name="password"
required
autoComplete="new-password"
value={passwordState}
onChange={onPasswordChangeHandler}
/>
</InputGroup>
</FormGroup>
<div className="custom-control custom-control-alternative custom-checkbox">
<input
className="custom-control-input"
id=" customCheckLogin"
type="checkbox"
/>
<label
className="custom-control-label"
htmlFor=" customCheckLogin"
>
<span className="text-muted">Remember me</span>
</label>
</div>
<div className="text-center">
<Button className="my-4" color="primary" type="submit">
Sign in
</Button>
</div>
</Form>
</CardBody>
</Card>
<Row className="mt-3">
<Col xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Forgot password?</small>
</a>
</Col>
<Col className="text-right" xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Create new account</small>
</a>
</Col>
</Row>
</Col>
</>
);
};
export default Login;
Option # 3: Using both React hooks (useRef & useState).
You could use the useRef React hook for focusing purposes only and also use a local state value, using the useState React hook, for the usual purposes of login in.
Option # 4: Using custom hooks.
You can use all the mentioned before, but using primordially a custom hook, which uses the useReducer React hook under the trunk, and then useRef for focusing and useState for other purposes:
Coder example:
Custom hook:
import {useReducer} from "react";
const initialInputState = {
valueState: '',
valueIsTouchedState: false,
};
const inputStateReducer = (state, action) => {
if (action.type === 'SET_VALUE_IS_TOUCHED_STATE') {
return {
valueState: state.valueState,
valueIsTouchedState: action.payload.valueIsTouchedState
};
}
if (action.type === 'SET_VALUE_STATE') {
return {
valueState: action.payload.valueState,
valueIsTouchedState: state.valueIsTouchedState
};
}
return initialInputState;
};
const useInputReducer = (valueValidator) => {
const [inputState, dispatchFunction] = useReducer(inputStateReducer, initialInputState);
const valueIsValidState = valueValidator(inputState.valueState);
const valueInputIsInvalid = (!valueIsValidState && inputState.valueIsTouchedState);
const valueInputChangeHandler = (event) => {
dispatchFunction({type: 'SET_VALUE_IS_TOUCHED_STATE', payload: {valueIsTouchedState: true}});
dispatchFunction({type: 'SET_VALUE_STATE', payload: {valueState: event.target.value}});
};
const valueInputBlurHandler = (event) => {
dispatchFunction({type: 'SET_VALUE_IS_TOUCHED_STATE', payload: {valueIsTouchedState: true}});
// setValueState(event.target.value);
};
const setValueIsTouchedState = (value) => {
dispatchFunction({type: 'SET_VALUE_IS_TOUCHED_STATE', payload: {valueIsTouchedState: value}});
};
const resetValueInput = () => {
dispatchFunction({type: 'SET_VALUE_STATE', payload: {valueState: ''}});
dispatchFunction({type: 'SET_VALUE_IS_TOUCHED_STATE', payload: {valueIsTouchedState: false}});
};
return {
valueState: inputState.valueState,
setValueIsTouchedState,
valueIsValidState,
valueInputIsInvalid,
valueInputChangeHandler,
valueInputBlurHandler,
resetValueInput,
};
};
export default useInputReducer;
Form:
import {Fragment, useRef, useState} from 'react';
import {Prompt} from "react-router-dom";
import useInputReducer from "../../hooks/use-input-reducer";
import * as validators from "../../tools/validators";
import styles from './AuthForm.module.css';
const AuthForm = () => {
const [isLogin, setIsLogin] = useState(true);
const [startedToWork, setStartedToWork] = useState(false);
const {
valueState: emailState,
setValueIsTouchedState: setEmailIsTouchedState,
valueIsValidState: emailIsValidState, valueInputIsInvalid: emailInputIsInvalid,
valueInputChangeHandler: emailInputChangeHandler,
// valueInputBlurHandler: emailInputBlurHandler,
resetValueInput: resetEmailInput,
} = useInputReducer(validators.emailValidator);
const {
valueState: passwordState,
setValueIsTouchedState: setPasswordIsTouchedState,
valueIsValidState: passwordIsValidState, valueInputIsInvalid: passwordInputIsInvalid,
valueInputChangeHandler: passwordInputChangeHandler,
// valueInputBlurHandler: passwordInputBlurHandler,
resetValueInput: resetPasswordInput,
} = useInputReducer(validators.nameValidator);
const formIsValid = (emailIsValidState && passwordIsValidState);
const emailInputRef = useRef();
const passwordInputRef = useRef();
const submitFormHandler = (event) => {
event.preventDefault();
setEmailIsTouchedState(true);
setPasswordIsTouchedState(true);
emailInputRef.current.focus();
if (!formIsValid) {
setProperFocus();
return;
}
console.log('Submitted!. I did something!!');
const email = emailInputRef.current.value;
const password = passwordInputRef.current.value;
resetEmailInput();
resetPasswordInput();
};
const setProperFocus = () => {
if (emailInputIsInvalid) {
emailInputRef.current.focus();
} else if (passwordInputIsInvalid) {
passwordInputRef.current.focus();
}
}
const switchAuthModeHandler = () => {
setIsLogin((prevState) => !prevState);
};
const onStartedToWorkHandler = () => {
setStartedToWork(true);
};
const onFinishEnteringHandler = () => {
setStartedToWork(false);
};
const emailValidityClasses = `${styles.control}${emailInputIsInvalid ? ` ${styles.invalid}` : ''}`;
const passwordValidityClasses = `${styles.control}${passwordInputIsInvalid ? ` ${styles.invalid}` : ''}`;
return (
<Fragment>
<Prompt
when={startedToWork}
message={location =>
`Are you sure you want to go to "${location.pathname}"? \n All your entered data will be lost.`
}
/>
<section className={styles.auth}>
<h1>{isLogin ? 'Login' : 'Sign Up'}</h1>
<form
onSubmit={submitFormHandler}
onChange={onStartedToWorkHandler}
>
<div className={emailValidityClasses}>
<label htmlFor='email'>Your Email</label>
<input
type='email'
id='email'
name='email'
required
autoFocus={true}
ref={emailInputRef}
value={emailState}
onChange={emailInputChangeHandler}
// onBlur={emailInputBlurHandler}
/>
{emailInputIsInvalid ? <p className={styles['error-text']}>The Email must be valid.</p> : <p> </p>}
</div>
<div className={passwordValidityClasses}>
<label htmlFor='password'>Your Password</label>
<input
type='password'
id='password'
required
autoComplete="on"
ref={passwordInputRef}
value={passwordState}
onChange={passwordInputChangeHandler}
// onBlur={passwordInputBlurHandler}
/>
{passwordInputIsInvalid ? <p className={styles['error-text']}>The Password must not be empty.</p> : <p> </p>}
</div>
<div className={styles.actions}>
<button onClick={onFinishEnteringHandler}>{isLogin ? 'Login' : 'Create Account'}</button>
<button
type='button'
className={styles.toggle}
onClick={switchAuthModeHandler}
>
{isLogin ? 'Create new account' : 'Login with existing account'}
</button>
</div>
</form>
</section>
</Fragment>
);
};
export default AuthForm;
I never do react js but i code react native.
I think you can store the input in the state using onChangeText like this
using hooks
const index = ()=>{
const {state,setState} = useState('');
return <TextInput onChangeText={(txt)=>{
setState(txt);
console.log(state); }} />
}

How do I get the value from Form.Control in React Bootstrap?

Here is my code :
<Modal centered size="lg" show={showAlertModal} onHide={handleCloseAlertModal}>
<Modal.Header>
<Modal.Title>{dpAlert !== null && dpAlert.id !== null ? `Alert #${dpAlert.id} - Editing` : `New Alert`}</Modal.Title>
</Modal.Header>
<Form onSubmit={handleSubmit}>
<Modal.Body>
<Form.Group controlId="language">
<Form.Label>Language</Form.Label>
<Form.Control id='inputL' onChange={(value) => setInputLanguage} type="text" placeholder="Language" required />
<Form.Text className="text-muted">
This is used for internal reference only, not shown to the public
</Form.Text>
</Form.Group>
<hr />
<b>Preview:</b>
{getAlertPreview(dpAlert)}
</Modal.Body>
<Modal.Footer>
<Button type="reset" variant="danger" size="lg" onClick={handleCloseAlertModal}>
Close
</Button>
<Button type="submit" variant="primary" size="lg" onClick={handleSubmit} form="newAlert">
Save
</Button>
</Modal.Footer>
</Form>
</Modal>
I am trying to get the value from
<Form.Control id='inputL' onChange={(value) => setInputLanguage} type="text" placeholder="Language" required />
and I have tried the onChange to set the value in a state but it's not working? Any help is appreciated thank you
You can get with event.target.value
const setInputLanguage = event => {
console.log(event.target.value);
}
<Form.Control id='inputL' onChange={(value) => setInputLanguage} type="text" placeholder="Language" required />
OR
<Form.Control id='inputL' onChange={event => console.log(event.target.value)} type="text" placeholder="Language" required />

Bootstrap Modal goes blank after button click

I am trying to call a Modal function. When I click to view it, it doesn't render and the page goes blank(white).
This is the code for
BootstrapModal :
class BootstrapModal extends React.Component{
constructor(){
super();
this.state = {
showHide : false
}
}
handleModalShowHide() {
console.log("hitting");
this.setState({ showHide: !this.state.showHide })
}
render(){
return(
<div>
<Button variant="third" id="btn-third" onClick={() => this.handleModalShowHide()}>
Send Email
</Button>
<Modal show={this.state.showHide}>
<Modal.Header closeButton onClick={() => this.handleModalShowHide()}>
<Modal.Title>Email Chart To User</Modal.Title>
</Modal.Header>
<Modal.Body>
<FormGroup>
<Modal.Label>Email address</Modal.Label>
<Modal.Input
type="email"
placeholder="Email"
/>
</FormGroup>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={() => this.handleModalShowHide()}>
Cancel
</Button>
<Button variant="primary" onClick={() => this.handleModalShowHide()}>
Send
</Button>
</Modal.Footer>
</Modal>
</div>
)
}
}
export default BootstrapModal;
Any ideas on why this is happening? Any suggestions would be gladly appreciated.
I think your problem is that you have not binded the handleModalShowHide() function. You can aviod having to do thst using an arrow function:
handleModalShowHide = () => {
Code here
}
I had to change
<FormGroup>
<Modal.Label>Email address</Modal.Label>
<Modal.Input
type="email"
placeholder="Email"
/>
</FormGroup>
To
<FormGroup>
<label for="message-text" class="col-form-label">Email Adress:</label>
<input type="text" class="form-control" id="recipient-name"></input>
</FormGroup>
After changing this, the Modal successfully rendered.

Categories