Displaying multiple PDF files in reactjs - javascript

I am new to react and I have multiple pdfs that I am trying to display depending on the link selected. I have managed to display a PDF from a selectable list of links of my PDFs stored inside the src directory. However, the same pdf appears for all the links. When I try to display different pdfs, I get this error:
.
For PDF viewing I used the code from here:
https://npm.io/package/react-pdf
My question is how can I implement such a case where I can display a different pdf depending on the link I would have clicked.
My code to display the pdf depending on the link looks like this:
import React, { Component, useState } from "react";
import { Document, Page } from "react-pdf";
import myPdf from '../../../components/pdf/signed.pdf'
import ViewPdf from '../../../components/ViewPdf'
import ViewSecondPdf from '../../../components/ViewPdf2'
import ViewThirdPdf from '../../../components/ViewPdf3'
import AllPages from "src/components/pdf/AllPages";
import { Table, Col, Row, Button } from 'reactstrap'
import { Link } from "react-router-dom";
const Display = (props) => {
<div>
<AllPages pdf={props} />
</div>
}
const DocTable = ({ onToggle }) => {
return (
<>
<Link to="/sign" className="mb-2"><span className="material-icons">keyboard_backspace</span></Link><br />
<span style={{ fontWeight: 'bold' }}>Documents</span><br />
<Table bordered hover size="sm">
<thead>
<br />
<tr>
<th>ID</th>
<th>Document Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">001</th>
<td><Button id="MICButton" name="MICButton" color="link" onClick={onToggle}>Vehicle Insurance Claim</Button></td>
<td>Signed</td>
</tr>
<tr>
<th scope="row">002</th>
<td><Button id="HIButton" name="HIButton" color="link" onClick={onToggle}>Household Insurance Contract</Button></td>
<td>Signed</td>
</tr>
<tr>
<th scope="row">003</th>
<td><Button id="CIButton" name="CIButton" color="link" onClick={onToggle}>Vehicle Insurance Contract</Button></td>
<td>Not Signed</td>
</tr>
</tbody>
</Table>
<br />
</>
);
}
const DocumentList = () => {
const [isVisible, setIsVisible] = useState(false) // false to hide the PDF for the first time
const handleToggle = () => {
setIsVisible(prevState => !prevState)
}
if(document.getElementById('MICButton').onToggle == true){
return (
<div>
<Row>
<Col xs="6">
<DocTable isVisible={isVisible} onToggle={handleToggle} />
</Col>
<Col xs="6">
{isVisible && <ViewPdf />}
</Col>
</Row>
</div>
);
}
if(document.getElementById('HIButton').onToggle == true){
return (
<div>
<Row>
<Col xs="6">
<DocTable isVisible={isVisible} onToggle={handleToggle} />
</Col>
<Col xs="6">
{isVisible && <ViewSecondPdf />}
</Col>
</Row>
</div>
);
}
if(document.getElementById('CIButton').onToggle == true){
return (
<div>
<Row>
<Col xs="6">
<DocTable isVisible={isVisible} onToggle={handleToggle} />
</Col>
<Col xs="6">
{isVisible && <ViewThirdPdf />}
</Col>
</Row>
</div>
);
}
}
export default DocumentList

You could pass the PDF ID to the onToggle and then, depending on it, display the required component
const DocTable = ({ onToggle }) => {
return (
<>
<Link to="/sign" className="mb-2">
<span className="material-icons">keyboard_backspace</span>
</Link>
<br />
<span style={{ fontWeight: 'bold' }}>Documents</span>
<br />
<Table bordered hover size="sm">
<thead>
<br />
<tr>
<th>ID</th>
<th>Document Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">001</th>
<td>
<Button id="MICButton" name="MICButton" color="link" onClick={() => onToggle('MICButton')}>
Vehicle Insurance Claim
</Button>
</td>
<td>Signed</td>
</tr>
<tr>
<th scope="row">002</th>
<td>
<Button id="HIButton" name="HIButton" color="link" onClick={() => onToggle('HIButton')}>
Household Insurance Contract
</Button>
</td>
<td>Signed</td>
</tr>
<tr>
<th scope="row">003</th>
<td>
<Button id="CIButton" name="CIButton" color="link" onClick={() => onToggle('CIButton')}>
Vehicle Insurance Contract
</Button>
</td>
<td>Not Signed</td>
</tr>
</tbody>
</Table>
<br />
</>
);
};
const DocumentList = () => {
const [isVisible, setIsVisible] = useState(false); // false to hide the PDF for the first time
const [activeDoc, setActiveDoc] = useState(null);
const handleToggle = (docID) => {
setIsVisible((prevState) => !prevState);
setActiveDoc(docID);
};
return (
<div>
<Row>
<Col xs="6">
<DocTable isVisible={isVisible} onToggle={handleToggle} />
</Col>
<Col xs="6">
{(() => {
if(!isVisible){
return null
}
switch (activeDoc) {
case 'MICButton':
return <ViewPdf />;
case 'HIButton':
return <ViewSecondPdf />;
case 'CIButton':
return <ViewThirdPdf />;
default:
return null;
}
})()}
</Col>
</Row>
</div>
);
};

Related

Multiple handle change

i am working on project which contains more than 200 input fields for list.is it possible to manage them with single state input
import { useState } from "react";
import Item from "../Components/Item";
const initialState={
input:''
}
const List = () => {
const [values,setValues]=useState(initialState)
const handleChange=(e)=>{
setValues({
...values,[e.target.name]:e.target.value
})
}
return (
<div className="container">
<div className="listhead">
<h3 className="text-center">Price List-2022</h3>
<table className="table table-bordered border-dark table-hover text-center">
<thead className="bg-success text-white table-bordered border-dark">
<tr>
<th>S.No</th>
<th>Item</th>
<th>Price</th>
<th>Qty</th>
<th>Total</th>
</tr>
</thead>
<Item
product="bomb"
name="input"
price="50"
value={values.input}
handleChange={handleChange}
/>
<Item
product="chakkar"
name="input"
price="100"
value={values.input}
handleChange={handleChange}
/>
</table>
</div>
</div>
);
};
export default List;
child element
const Item = ({name,product,price,value,handleChange}) => {
return (
<tbody>
<tr>
<th>1</th>
<th>{product}</th>
<th>{price}</th>
<th className="w-25">
<input
name={name}
value={value}
onChange={handleChange}
type='number'
/>
</th>
<th> </th>
</tr>
</tbody>
);
};
export default Item;
with this code if i enter values in input fields all other input fields reads the same value. if i need to create 200 input field with data, what are the ways to do that?
You can pass all values to item
like this :
<Item
name="input"
price="50"
value={values}
handleChange={handleChange}
/>
and in Item component set props of input like this :
<input
name={name}
value={values[name]}
onChange={handleChange}
type='number'
/>
Your inputs have the same name, if you want to set the state for the different inputs you'll need a unique identifier.
This way you can use the e.target.name as a key in your state object.
<Item
product="Something"
name={"unique identifier"}
price="50"
value={values["unique identifier"]}
handleChange={handleChange}
/>
A good practice is also to use the callback function with the useState to make sure you have the most recent values.
setValues((prevValues) => {
return {
...prevValues,
[e.target.name]: e.target.value,
};
});
``

× TypeError: Cannot read properties of undefined (reading 'form')

I am trying to trigger the handleSubmit function for the form but getting the error mentioned in the title. Adding the code for the handle submit function as well as the form below. Please help out
I am using a react template from CoreUI for this so most tags are from that. The form will be nested under the CCard Tag and the submit button is in the Card footer. I have the form in a separate component and i am storing the values in the state which are to be passed to the post api call on submit which is inside the handle submit function
const DataSources = () => {
const [collapsed, setCollapsed] = React.useState(true)
const [showElements, setShowElements] = React.useState(true)
const entryList = []
const [tableEntries, setTableEntries] = React.useState(entryList)
function handleSubmit(){
// POST request using axios with set headers
const article = { "connectionType":"InstagramConnection","id":"e5ee8320-a307-448b-a0ed-0829a187050f","name":this.state.value,"accessCredentials":{"id":2,"token":this.state.access_token} };
const headers = {
"Content-Type": "application/json; charset=utf-8"
};
Axios.post('http://localhost:8080/api/connections', article, { headers })
.then(response => console.log(response.data.id));
};
useEffect(() => {
Axios.get('http://localhost:8080/api/connections')
.then(res => {
console.log(res.data);
const newList = entryList.concat(res.data);
Array.prototype.forEach.call(res.data, response => {
setTableEntries(prevTableEntries => [...prevTableEntries,response]);
});
console.log(tableEntries);
})
.catch(err => console.log(err));
}, []);
return (
<>
<CRow>
<CCol xs="12" md="10">
<p className="h1">Data Sources</p>
</CCol>
<CCol xs="12" md="2">
<CDropdown className="m-1" size="lg" align="center" size="lg">
<CDropdownToggle color="secondary">
Select Client
</CDropdownToggle>
<CDropdownMenu>
<CDropdownItem>Client 1</CDropdownItem>
<CDropdownItem>Client 2</CDropdownItem>
</CDropdownMenu>
</CDropdown>
</CCol>
</CRow>
<br></br>
<CRow>
<CCol xs="12" md="4">
<CCard>
<CCardHeader>
Add Data Source
</CCardHeader>
<CCardBody>
<CForm ref={ (ref) => { this.form = ref; } } className="form-horizontal" onSubmit={handleSubmit}>
<CFormGroup>
<Facebook />
</CFormGroup>
</CForm>
</CCardBody>
<CCardFooter>
<CButton type="submit" size="sm" color="primary" value="Submit" onClick={ () => { this.form.dispatchEvent(new Event('submit')) } }><CIcon name="cil-scrubber" /> Add Connection</CButton>
<CButton type="reset" size="sm" color="danger"><CIcon name="cil-ban" /> Reset</CButton>
</CCardFooter>
</CCard>
</CCol>
<CCol xs="12" md="8">
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Id</th>
<th scope="col">App Name</th>
<th scope="col">Connection Type</th>
<th scope="col">Options</th>
</tr>
</thead>
<tbody>
{tableEntries.map((item) => (
<>
<tr>
<th scope="row">1</th>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.connectionType}</td>
<td>
<CDropdown className="m-1" size="lg">
<CDropdownToggle color="secondary">
Select Option
</CDropdownToggle>
<CDropdownMenu>
<CDropdownItem>Delete</CDropdownItem>
<CDropdownItem>Reauthorize</CDropdownItem>
</CDropdownMenu>
</CDropdown>
</td>
</tr>
</>
))}
</tbody>
</table>
</CCol>
</CRow>
</>
)
}

Row click react.js

this component react presents a table with its own row id, what I want to do is to have the possibility to select the row with the mouse-click at the user's click, how can I implement this within this react application? The table loads a series of values ​​from the backend which then displays with reactstrap, how can I fix this?
React.js Code:
class Static extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
this.state = {
tableStyles: [
],
};
this.checkAll = this.checkAll.bind(this);
}
parseDate(date) {
this.dateSet = date.toDateString().split(" ");
return `${date.toLocaleString("en-us", { month: "long" })} ${
this.dateSet[2]
}, ${this.dateSet[3]}`;
}
checkAll(ev, checkbox) {
const checkboxArr = new Array(this.state[checkbox].length).fill(
ev.target.checked
);
this.setState({
[checkbox]: checkboxArr,
});
}
//Function create user
async newuser(event){
let ragionesocialetext = event.target.value;
console.log("Ragione Sociale: "+ragionesocialetext);
}
//Function call con text change
async handleChange(event) {
let searchtext = event.target.value;
var result=await ricercaclienti(searchtext);
var results=[];
for(var i=0; i<result.length; i++){
var value={
id: result[i].IdCliente,
picture: require("../../../images/cliente.jpg"), // eslint-disable-line global-require
description: result[i].RagioneSociale,
info: {
citta: result[i].Citta,
provincia: result[i].Provincia,
},
DataInserimento: result[i].DataInserimento,
Cap: result[i].Cap,
progress: {
percent: 30,
colorClass: "warning",
}
};
results.push(value);
}
this.setState({tableStyles: results});
}
render() {
return (
<div className={s.root}>
<h2 className="page-title">
Clienti - <span className="fw-semi-bold"> Anagrafia</span>
</h2>
<Row>
<Col>
<Widget
settings
close
bodyClass={s.mainTableWidget}
>
<p></p>
<p></p>
<p></p>
<p></p>
<FormGroup >
<InputGroup className="input-group-no-border">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="fa fa-search text-white" />
</InputGroupText>
</InputGroupAddon>
<Input
id="search-input"
className="input-transparent"
placeholder="Ricerca"
type='text'
name='ricerca'
onChange={this.handleChange.bind(this)}
/>
</InputGroup>
</FormGroup>
<Table striped>
<thead>
<tr className="fs-sm">
<th className="hidden-sm-down">#</th>
<th>Cliente</th>
<th>Ragione Sociale</th>
<th className="hidden-sm-down">Indirizzo</th>
<th className="hidden-sm-down">Data Inserimento</th>
<th className="hidden-sm-down">CAP</th>
<th className="hidden-sm-down">Stato</th>
</tr>
</thead>
<tbody>
{this.state.tableStyles.map((row) => (
<tr key={row.id}>
<td>{row.id}</td>
<td>
<img
className="img-rounded"
src={row.picture}
alt=""
height="50"
/>
</td>
<td>
{row.description}
{row.label && (
<div>
<Badge color={row.label.colorClass}>
{row.label.text}
</Badge>
</div>
)}
</td>
<td>
<p className="mb-0">
<small>
Città:
<span className="text-muted fw-semi-bold">
{row.info.citta}
</span>
</small>
</p>
<p>
<small>
Provincia:
<span className="text-muted fw-semi-bold">
{row.info.provincia}
</span>
</small>
</p>
</td>
<td className="text-muted">{row.DataInserimento}</td>
<td className="text-muted">{row.Cap}</td>
<td className="width-150">
<Progress
color={row.progress.colorClass}
value={row.progress.percent+row.i}
className="progress-sm mb-xs"
/>
</td>
</tr>
))}
</tbody>
</Table>
<div className="clearfix">
<div className="float-right">
<Button color="default" className="mr-2" size="sm">
Refresh...
</Button>
<UncontrolledButtonDropdown>
<DropdownToggle
color="inverse"
className="mr-xs"
size="sm"
caret
>
Nuovo Cliente
</DropdownToggle>
<DropdownMenu>
<DropdownItem>Inserisci ragione sociale</DropdownItem>
<Input
id="search-input"
className="input-transparent"
placeholder="ragionesociale"
type='text'
name='ragionesociale'
onChange={this.newuser.bind(this)}
/>
</DropdownMenu>
</UncontrolledButtonDropdown>
</div>
<p></p>
</div>
</Widget>
</Col>
</Row>
</div>
);
}
}
You should set a selectedRowId variable in your state, then add
onClick={() => {this.setState({ selectedRowId: row.id })}}
prop to wherever the user should click to select the row. If you want to change the styles of the row based on if it is selected or not, you can change the class of the row element by adding
className={this.state.selectedRowId===row.id?'selected':'unselected'}
then adding styles for a selected and unselected class.

if ternario does not work, function has value but never used says

I am new with programing and I want to use if ternario, but it doesn't work. I have two functions and I create a third function to show one of them or the other. It is an application in ReactJS. Below is the code:
import { Table } from "react-bootstrap";
import { Link } from "react-router-dom";
import { useCartContext } from "../../Context/CartContext";
const emptyCart = () => {
return(
<>
<div>
<h3>The Cart is empty</h3>
<p>
Return to home to see our products
</p>
<Link to='/' ><button className="btn btn-info"> Home </button></Link>
</div>
</>
);
};
const CartFunction = () => {
const { list, totalPrice } = useCartContext();
return (
<Table striped hover>
<thead>
<tr>
<th>Product</th>
<th>Title</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{list.map((varietal) => (
<tr key={varietal.id}>
<td>
<img
src={varietal.pictureUrl}
alt='img'
style={{ width: "82px" }}
/>
</td>
<td>{varietal.title}</td>
<td>{varietal.count}</td>
<td>${varietal.price}</td>
</tr>
))}
</tbody>
<thead>
<tr>
<td colSpan="3">Total</td>
<td>${totalPrice()}</td>
</tr>
</thead>
</Table>
);
};
const CartComponent = () => {
const { list } = useCartContext();
return (
<>
{list.length !== 0 ? <CartFunction /> : <emptyCart />}
</>
);
};
export default CartComponent;
Visual Code it says that emptyCard has a value but it is never used. If there is someone that could help me I would appreciate it. Cheers

ReactJS Modal component won't close onclick

I have created a user CRUD api that is linked to a reactJs front end. I have been using the bootstrap components and decied to use the modal component to have edit forms. The only issue is that for some reason when the modal opens, I can not exit it again unless I reload the browser.
The code for the EditUserModal.js is as follows:
import React, { Component } from 'react';
import {Modal, Button, Row, Col, Form} from 'react-bootstrap';
import * as moment from 'moment';
const BASE_API_URL = `http://localhost:56062/api/users`;
var currentDate = new Date();
export class EditUserModal extends Component{
constructor(props){
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount(){
}
handleSubmit(event){
event.preventDefault();
fetch(BASE_API_URL,{
method:'PUT',
headers:{
'Accept':'application/json',
'Content-Type':'application/json'
},
body:JSON.stringify({
Id: event.target.Id.value,
firstName: event.target.firstName.value,
lastName: event.target.lastName.value,
Email: event.target.Email.value,
mobileNumber: event.target.mobileNumber.value,
dateOfBirth: event.target.dateOfBirth.value,
lastModified: currentDate
})
})
.then(res=> res.json())
.then((result) =>
{
console.log(result);
},
(error) => {
console.log('Failed')
}
)
}
render(){
return(
<Modal
{...this.props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
Edit User
</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="editFormContainer">
<Row>
<Col sm={12}>
<Form onSubmit={this.handleSubmit}>
<Form.Group controlId="Id">
<Form.Label>User ID</Form.Label>
<Form.Control name="Id" disabled defaultValue = {this.props.userid} type="text" placeholder="Id" />
</Form.Group>
<Form.Group controlId="firstName">
<Form.Label>First Name</Form.Label>
<Form.Control name="firstName" required type="text" defaultValue = {this.props.firstname} placeholder="First Name" />
</Form.Group>
<Form.Group controlId="lastName">
<Form.Label>Last Name</Form.Label>
<Form.Control name="lastName" required type="text" defaultValue = {this.props.lastname} placeholder="Last Name" />
</Form.Group>
<Form.Group controlId="Email">
<Form.Label>Email address</Form.Label>
<Form.Control name="Email" required type="email" defaultValue = {this.props.useremail} placeholder="Email e.g. name#example.com" />
</Form.Group>
<Form.Group controlId="mobileNumber">
<Form.Label>Mobile Number</Form.Label>
<Form.Control name="mobileNumber" required type="text" defaultValue = {this.props.mobilenumber} placeholder="Mobile e.g. 0723218223 or +447236475886" />
</Form.Group>
<Form.Group controlId="dateOfBirth">
<Form.Label>Date of Birth</Form.Label>
<Form.Control name="dateOfBirth" required type="date" defaultValue = {moment(new Date(this.props.dateofbirth)).format('YYYY-MM-DD')} placeholder="Date of Birth e.g. 05-02-97" />
</Form.Group>
<Form.Group>
<Button variant="primary" type="submit">Edit User</Button>
</Form.Group>
</Form>
</Col>
</Row>
</div>
</Modal.Body>
<Modal.Footer>
<Button variant="danger" onClick={this.props.onHide}>Close</Button>
</Modal.Footer>
</Modal>
)
}
}
And then for the page the modal is used, the code related is as follows:
export class User extends Component {
constructor(props){
super(props);
this.state = {users:[], addModalShow : false, editModalShow: false}
}
render(){
const {users, userid, firstname, lastname, useremail, mobilenumber, dateofbirth, lastmodified} = this.state;
let addModalClose =() => this.setState({addModalShow:false});
let editModalClose =() => this.setState({editModalShow:false});
return(
<div>
<ButtonToolbar>
<Button variant='outline-dark' style={{margin:"auto"}} onClick={()=> this.setState({addModalShow:true})}>
Add User
</Button>
<AddUserModal show={this.state.addModalShow} onHide={addModalClose} />
</ButtonToolbar>
<Table responsive borderless style={{borderRadius:"0.3em"}} striped hover size="sm" variant="dark" className="mt-4">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Mobile Number</th>
<th>Date of Birth</th>
<th>Last Modified</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{users.map(user=>
<tr key = {user.Id}>
<td>{user.Id}</td>
<td>{user.firstName}</td>
<td>{user.lastName}</td>
<td>{user.Email}</td>
<td>{user.mobileNumber}</td>
<td>{moment(new Date(user.dateOfBirth)).format('YYYY-MM-DD')}</td>
<td>{user.lastModified}</td>
<td>
<ButtonToolbar>
<Button className="mr-2" variant="outline-light" onClick={()=> { ReactDOM.render(<EditUserModal show={true} userid={user.Id} firstname={user.firstName}
lastname={user.lastName} useremail={user.Email} mobilenumber={user.mobileNumber} dateofbirth={user.dateOfBirth} onHide = {editModalClose} /> , document.getElementById('root')) }}>
Edit User
</Button>
</ButtonToolbar>
</td>
<td>
<Button variant="outline-danger" onClick={()=> this.deleteUser(user.Id)} >Delete</Button>
</td>
</tr>
)}
</tbody>
</Table>
</div>
)
}
}
Why is the modal not exiting properly? or what way could i make this possible? Clicking off the modal, cancel or the X button don't seem to close the modal.
======================= EDIT =======================================
I realized, when the modal is in that state, and I submit the edit form, the console displays a "Failed" message from thi chunk of code, even though when I refresh the page, it successfully loads the new edited information.
handleSubmit(event){
event.preventDefault();
fetch(BASE_API_URL,{
method:'PUT',
headers:{
'Accept':'application/json',
'Content-Type':'application/json'
},
body:JSON.stringify({
Id: event.target.Id.value,
firstName: event.target.firstName.value,
lastName: event.target.lastName.value,
Email: event.target.Email.value,
mobileNumber: event.target.mobileNumber.value,
dateOfBirth: event.target.dateOfBirth.value,
lastModified: currentDate
})
})
.then(res=> res.json())
.then((result) =>
{
console.log(result);
},
(error) => {
console.log('Failed')
}
)
}
It's a sketch... but something like this:
export class User extends Component {
constructor(props){
super(props);
this.state = {users:[], addModalShow : false, editModalShow: false, currentEdited: null}
}
addModalClose =() => this.setState({addModalShow:false});
editModalClose =() => this.setState({editModalShow:false});
render(){
const {users, currentEdited} = this.state;
return(
<div>
<ButtonToolbar>
<Button variant='outline-dark' style={{margin:"auto"}} onClick={()=> this.setState({addModalShow:true})}>
Add User
</Button>
<AddUserModal show={this.state.addModalShow} onHide={this.addModalClose} />
</ButtonToolbar>
<Table responsive borderless style={{borderRadius:"0.3em"}} striped hover size="sm" variant="dark" className="mt-4">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Mobile Number</th>
<th>Date of Birth</th>
<th>Last Modified</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{users.map(user=>
<tr key = {user.Id}>
<td>{user.Id}</td>
<td>{user.firstName}</td>
<td>{user.lastName}</td>
<td>{user.Email}</td>
<td>{user.mobileNumber}</td>
<td>{moment(new Date(user.dateOfBirth)).format('YYYY-MM-DD')}</td>
<td>{user.lastModified}</td>
<td>
<ButtonToolbar>
<Button className="mr-2" variant="outline-light" onClick={()=> { this.setState({ currentEdited: user, editModalShow: true }); }}>
Edit User
</Button>
</ButtonToolbar>
</td>
<td>
<Button variant="outline-danger" onClick={()=> this.deleteUser(user.Id)} >Delete</Button>
</td>
</tr>
)}
</tbody>
</Table>
<EditUserModal show={this.state.editModalShow} onHide={this.editModalClose} {...currentEdited} />
</div>
)
}
}
It's because you have hardcoded show prop to true.
<EditUserModal show={this.state.editModalShow} {...otherProps} />
export class User extends Component {
constructor(props){
super(props);
this.state = {users:[], addModalShow : false, editModalShow: false}
}
render(){
const {users, userid, firstname, lastname, useremail, mobilenumber, dateofbirth, lastmodified} = this.state;
let addModalClose =() => this.setState({addModalShow:false});
let editModalClose =() => this.setState({editModalShow:false});
return(
<div>
<ButtonToolbar>
<Button variant='outline-dark' style={{margin:"auto"}} onClick={()=> this.setState({addModalShow:true})}>
Add User
</Button>
<AddUserModal show={this.state.addModalShow} onHide={addModalClose} />
</ButtonToolbar>
<Table responsive borderless style={{borderRadius:"0.3em"}} striped hover size="sm" variant="dark" className="mt-4">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Mobile Number</th>
<th>Date of Birth</th>
<th>Last Modified</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{users.map(user=>
<tr key = {user.Id}>
<td>{user.Id}</td>
<td>{user.firstName}</td>
<td>{user.lastName}</td>
<td>{user.Email}</td>
<td>{user.mobileNumber}</td>
<td>{moment(new Date(user.dateOfBirth)).format('YYYY-MM-DD')}</td>
<td>{user.lastModified}</td>
<td>
<ButtonToolbar>
<Button className="mr-2" variant="outline-light" onClick={()=> { this.setState({ editShowModal: true }); }}>
Edit User
</Button>
<EditUserModal show={this.state.editModalShow} userid={user.Id} firstname={user.firstName}
lastname={user.lastName} useremail={user.Email} mobilenumber={user.mobileNumber}
dateofbirth={user.dateOfBirth} onHide={editModalClose} />
</ButtonToolbar>
</td>
<td>
<Button variant="outline-danger" onClick={()=> this.deleteUser(user.Id)} >Delete</Button>
</td>
</tr>
)}
</tbody>
</Table>
</div>
)
}
}

Categories

Resources