Passing Props (img url ) using React-Modal (react js) - javascript

I need to pass image url to modal in react js. Like, on click the item from the "imgae attachment", it shows the modal with image for selected item. But it can't show my image data by passing img={item.document}, Here is my code below:
DepositRecord.js
import React, { Component } from "react";
import { Table } from "react-bootstrap";
import { Button, ButtonToolbar } from "react-bootstrap";
import { AddDepositModal } from "./AddDepositModal";
export class DepositRecord extends Component {
constructor(props) {
super(props);
this.state = { deps: [], addModalShow: false };
}
componentDidMount() {
this.refershList();
}
refershList() {
this.setState({
deps: [
{ id: 9, userId: "12", document: "img1_url" },
{ id: 8, userId: "16", document: "img2_url" },
{ id: 6, userId: "13", document: "img3_url" },
{ id: 4, userId: "1", document: "img4_url" },
{ id: 2, userId: "1", document: "img5_url" }
]
});
}
render() {
const { deps } = this.state;
let addModalClose = () => this.setState({ addModalShow: false });
return (
<div>
<h3>Customer's Deposit Record</h3>
<br />
<Table className="mt-4" striped bordered hover size="sm">
<thead>
<tr>
<th>Deposit id</th>
<th>user id</th>
<th>img attachment</th>
</tr>
</thead>
<tbody>
{deps.map((item) => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.userId}</td>
<td>
<ButtonToolbar>
<Button
variant="primary"
onClick={() => this.setState({ addModalShow: true })}
>
image attachment
</Button>
<AddDepositModel
show={this.state.addModalShow}
onHide={addModalClose}
img={item.document}
/>
</ButtonToolbar>
</td>
</tr>
))}
</tbody>
</Table>
</div>
);
}
}
export default DepositRecord;
AddDepositModal.js <--the Madal component
import React, { Component } from 'react';
import { Modal, Button, Row, Col, Form } from 'react-bootstrap';
export class AddDepositModal extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Modal
{...this.props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
Deposit Record
</Modal.Title>
</Modal.Header>
<Modal.Body>
<img src={this.props.img} width={700} height={1100}/>
</Modal.Body>
<Modal.Footer>
<Button variant="danger" onClick={this.props.onHide}>Close</Button>
</Modal.Footer>
</Modal>
);
}
}
export default AddDepositModal;
My Problem: I am not able to pass the image URL to a Modal component and have no better idea solving it in this code.
Please help me and if any including, changes or complete solution for perfect understanding for the requirement would be really great. Many Thanks in Advance!

Hello here's your solution
DepositRecord.js
import React, { useEffect, useState } from "react";
import { Button, ButtonToolbar, Table } from "react-bootstrap";
import AddDepositModal from "./AddDeposiModal";
const DepositRecord = () => {
const [deps, setDeps] = useState([]);
const [visibleModal, setVisibleModal] = useState(false);
const [depImage, setDepImage] = useState(null);
useEffect(() => {
loadDepsHandler();
}, []);
const loadDepsHandler = () => {
const myRequest = new Request("https://randomuser.me/api/", {
method: "GET",
cache: "default",
});
debugger;
fetch(myRequest)
.then((res) => res.json())
.then((data) => {
const { results } = data;
setDeps(results);
})
.catch((err) => console.log(err));
};
const setDepHandler = (id) => {
const dep = deps.find((a) => a.id.value === id);
debugger;
setDepImage(dep.picture.large);
setVisibleModal(true);
};
return (
<div>
<h3>Customer's Deposit Record</h3>
<br />
<Table className="mt-4" striped bordered hover size="sm">
<thead>
<tr>
<th>Deposit id</th>
<th>user name</th>
<th>img attachment</th>
</tr>
</thead>
<tbody>
{deps.map((item) => (
<tr key={item.id.name}>
<td>{item.id.name}</td>
<td>{item.value}</td>
<td>
<ButtonToolbar>
<Button
variant="primary"
onClick={() => setDepHandler(item.id.value)}
>
image attachment
</Button>
</ButtonToolbar>
</td>
</tr>
))}
</tbody>
</Table>
{visibleModal && (
<AddDepositModal
show={visibleModal}
onHide={() => setVisibleModal(false)}
image={depImage}
/>
)}
</div>
);
};
export default DepositRecord;
AddDepositModal.js
import React from "react";
import { Button, Modal } from "react-bootstrap";
const AddDepositModal = ({ show, onHide, image }) => {
return (
<Modal show={show} onHide={onHide}>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
Deposit Record
</Modal.Title>
</Modal.Header>
<Modal.Body>
<img src={image} width={700} height={1100} alt={image} />
</Modal.Body>
<Modal.Footer>
<Button variant="danger" onClick={onHide}>
Close
</Button>
</Modal.Footer>
</Modal>
);
};
export default AddDepositModal;
Async call added. This API is public so it's will take some time to get results
.

Related

Converting class component to functional component Props in Functional component not passing properly and Query not being received

Hey I am trying to covert a class component into a functional component and for some reason the props I'm passing into the form component are being passed as object values. The original class component works fine but I am not sure what is causing this issue with props. what it looks like with
what it should look like with class component:
what I currently have with functional component:
function component home page
import React from "react";
// import Jumbotron from "react-bootstrap/Jumbotron";
import Row from "react-bootstrap/Row";
import Card from "../components/Card";
import Form from "../components/Form";
import Col from "react-bootstrap/Col";
import Container from "react-bootstrap/Container";
import Jumbotron from "react-bootstrap/Jumbotron";
import { useState } from "react";
import API from "../utils/API";
import Book from "../components/Book";
import Button from "react-bootstrap/Button";
import { List } from "../components/List";
import Footer from "../components/Footer";
import "./style.css";
export default function Home() {
let [books, setBooks] = useState([]);
let [q, setQ] = useState("");
let [message, setMessage] = useState("Search For A Book to Begin");
// const handleInputChange = (event) => {
// let { name, value } = event.target;
// setQ(([name] = value));
// };
const handleInputChange = (event) => {
setQ(event.target.value)
};
let getBooks = () => {
API.getBooks(q)
.then((res) => setBooks(res.data))
.catch(() => setBooks([]));
setMessage("No New Books Found, Try a Different Query");
};
const handleFormSubmit = (event) => {
event.preventDefault();
getBooks();
};
let handleBookSave = (id) => {
const book = books.find((book) => book.id === id);
API.saveBook({
googleId: book.id,
title: book.volumeInfo.title,
subtitle: book.volumeInfo.subtitle,
link: book.volumeInfo.infoLink,
authors: book.volumeInfo.authors,
description: book.volumeInfo.description,
image: book.volumeInfo.imageLinks.thumbnail,
}).then(() => getBooks());
};
return (
<div>
<Container>
<Row>
<Col md={12}>
<Jumbotron className="rounded-3 mt-4">
<h1 className="text-center ">
<strong>(React) Google Books Search</strong>
</h1>
<h2 className="text-center">
Search for and Save Books of Interest.
</h2>
</Jumbotron>
</Col>
<Col md={12}>
<Card title="Book Search" icon=" fa-book">
<Form
handleInputChange={handleInputChange}
handleFormSubmit={handleFormSubmit}
q={q}
/>
</Card>
</Col>
</Row>
<Row>
<Col md={12}>
<Card title="Results">
{books.length ? (
<List>
{books.map((book) => (
<Book
key={book.id}
title={book.volumeInfo.title}
subtitle={book.volumeInfo.subtitle}
link={book.volumeInfo.infolink}
authors={book.volumeInfo.authors.join(", ")}
description={book.volumeInfo.description}
image={book.volumeInfo.imageLinks.thumbnail}
Btn={() => (
<Button
onClick={() => handleBookSave(book.id)}
variant="primary"
className="ml-2"
>
Save
</Button>
)}
/>
))}
</List>
) : (
<h2 className="text-center">{message}</h2>
)}
</Card>
</Col>
</Row>
<Footer />
</Container>
</div>
);
}
Form component
import React from "react";
function Formmy({q, handleInputChange, handleFormSubmit }) {
return (
<form>
<div className="form-group">
<label htmlFor="Query">
<strong>Book</strong>
</label>
<input
className="form-control"
id="Title"
type="text"
value={q}
placeholder="Ready Player One"
name="q"
onChange={handleInputChange}
required
/>
</div>
<div className="float-end">
<button
onClick={handleFormSubmit}
type="submit"
className="btn btn-lg btn-danger float-right"
>
Search
</button>
</div>
</form>
);
}
export default Formmy;

can't render the products in proper order using nested map() & useEffect() in reactjs

I'm trying to build a restaurant web-app with Reactjs. I've parent categories, child categories, and products under child categories, I'm trying to build a UI with tabs where I can show the parent categories-clicked-show child categories & show the products under that child categories in proper order.
I'm getting the child categories when the parent is clicked, but I'm not getting the products as expected.
I want to render the product like this
Burger
Show all the burgers
Sandwich
show all the sandwich,
swarma
show all the sawrmas,
but instead im getting the swarmas only where i should get all the products in proper order.
Plz help me get the products in proper order.
This is my Menu.js
import React, { useEffect } from "react";
import MenuItems from "./MenuItems";
import "./testmenu.css";
// import burger from "../images/burger.jpg";
// import cake from "../images/cake-2.jpeg";
//Bootsrap
import { Container, Row, Col, Tab, Nav } from "react-bootstrap";
//REDUX
import { useSelector, useDispatch } from "react-redux";
import { getAllCategory } from "../actions";
import { Fragment } from "react";
const TestMenu = () => {
//GET ALL CATEGORIES WHEN RENDERED
const category = useSelector((state) => state.category);
console.log(category);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getAllCategory());
}, [dispatch]);
const renderParentCategories = (categories) => {
let parentCategories = [];
for (let category of categories) {
parentCategories.push(
<Nav.Item key={category.name}>
<Nav.Link eventKey={category.name}>{category.name}</Nav.Link>
</Nav.Item>
);
}
return parentCategories;
};
const renderChildrenCategories = (categories) => {
console.log(categories);
return categories.map((category, i) => (
<Tab.Pane key={i} eventKey={category.name}>
{category.children.map((cat, i) => (
<Fragment key={i}>
<h2>{cat.name}</h2>
<Row>{<MenuItems slug={cat.slug} />}</Row>
</Fragment>
))}
</Tab.Pane>
));
};
//CALLING THE LIST OF THE ITEMS
return (
<div className="Collections">
<Container>
<Tab.Container defaultActiveKey="first">
<Row>
<Col>
<Nav className="d-flex flex-row justify-content-center text-center">
{category.categories.length > 0
? renderParentCategories(category.categories)
: null}
</Nav>
</Col>
</Row>
<Row>
<Col>
<Tab.Content>
{category.categories.length > 0
? renderChildrenCategories(category.categories)
: null}
</Tab.Content>
</Col>
</Row>
</Tab.Container>
</Container>
</div>
);
};
export default TestMenu;
This is my MenuItems.js file:
import React, { useEffect } from "react";
import { Button, ButtonGroup, Col } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import { addToCart, getProductsBySlug } from "../actions";
import { generatePublicUrl } from "../urlConfig";
const MenuItems = ({ slug }) => {
const product = useSelector((state) => state.product);
const dispatch = useDispatch();
console.log(product);
useEffect(() => {
dispatch(getProductsBySlug(slug));
}, [dispatch, slug]);
return product.products.map((product, i) => (
<Col key={i} xs={6} md={3} lg={3} xl={3}>
<div className="menuitem">
<div className="images">
<img
className="image"
src={generatePublicUrl(product.productPictures[0].img)}
alt="img"
/>
<div className="menuitem__buttons">
<ButtonGroup size="sm">
{/* onClick={props.itemInfo} */}
<Button variant="info">
<i className="fa fa-info-circle" aria-hidden="true" />
Info
</Button>
{/* onClick={props.addItem} */}
<Button
variant="success"
onClick={() => {
const { _id, name, price } = product;
const img = product.productPictures[0].img;
// console.log(_id, name, price, img);
dispatch(addToCart( _id, name, price, img ));
}}
>
<i className="fas fa-shopping-cart" />
Add
</Button>
</ButtonGroup>
</div>
<span className="images__h3">
<h5 style={{ textAlign: "center" }}>{product.name}</h5>
<h5
style={{
color: "green",
textAlign: "center",
fontSize: "16px",
}}
>
Price: {product.price}tk
</h5>
</span>
</div>
</div>
</Col>
));
};
export default MenuItems;
Here is the console:
Here is the result I'm getting:

Open Dialog From Other Page In React

I'm opening a dialog component when i click the DELETE function button on my users list. When i click it, should show the dialog component. My problem is why i can't open it. I'm using redux to pass data to it.
Pls see this codesandbox link
CLICK HERE
import { dialogConstants } from "../constants";
export const initialState = {
title: null,
details: null,
isOpen: null
};
const dialogReducer = (state = initialState, action) => {
console.log(action.payload);
switch (action.type) {
case dialogConstants.SET_DIALOG_DETAILS:
return {
...state,
isOpen: action.payload.isOpen,
title: action.payload.title,
details: action.payload.details
};
default:
return state;
}
};
export default dialogReducer;
You are not importing Dialogs in user.js. So when you click button your dialog will not open. Try this:
In user.js:
...
import DeleteDialog from "./dialog";
import { useDispatch } from "react-redux";
import { deleteUser } from "./actions";
export default function User() {
const dispatch = useDispatch();
const [selectedUser, setSelectedUser] = React.useState({});
const [open, setDialogOpen] = React.useState(false);
const handleOnDelete = user => {
setSelectedUser(user);
setDialogOpen(true);
};
const handleOnAgree = () => {
// do action to handle on agree deleting an user
dispatch(deleteUser({ title: "Delete User", details: selectedUser }));
setDialogOpen(false);
};
return (
<div>
<Paper>
<TableContainer>
<Table stickyHeader aria-label="sticky table">
<TableHead>
<TableRow>
<TableCell>First Name</TableCell>
<TableCell>Last Name</TableCell>
<TableCell>Email Address</TableCell>
<TableCell>Actions</TableCell>
<TableCell />
</TableRow>
</TableHead>
<TableBody>
<TableRow>
<TableCell>JJJ</TableCell>
<TableCell>BBB</TableCell>
<TableCell>enfoie</TableCell>
<TableCell>
<Button variant="contained">Edit</Button>
<Button
variant="contained"
onClick={() => handleOnDelete({ id: 1, name: "JJJ" })}
>
Delete
</Button>
</TableCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
</Paper>
<DeleteDialog
user={selectedUser}
open={open}
onAgree={handleOnAgree}
onDisagree={() => setDialogOpen(false)}
/>
</div>
);
}
In dialog.js:
import React from "react";
import Button from "#material-ui/core/Button";
import Dialog from "#material-ui/core/Dialog";
import DialogActions from "#material-ui/core/DialogActions";
import DialogTitle from "#material-ui/core/DialogTitle";
import Slide from "#material-ui/core/Slide";
const Transition = React.forwardRef(function Transition(props, ref) {
return <Slide direction="up" ref={ref} {...props} />;
});
const DeleteDialog = ({ user, open, onAgree, onDisagree }) => {
return (
<div>
<Dialog
open={open}
TransitionComponent={Transition}
keepMounted
onClose={onDisagree}
aria-labelledby="alert-dialog-slide-title"
aria-describedby="alert-dialog-slide-description"
>
<DialogTitle id="alert-dialog-slide-title">
<span style={{ fontWeight: "bold" }}>
{" "}
User: {user.name} - {user.id}
</span>
</DialogTitle>
<DialogActions>
<Button variant="contained" size="small" onClick={onDisagree}>
Cancel
</Button>
<Button variant="contained" size="small" onClick={onAgree}>
Confirm
</Button>
</DialogActions>
</Dialog>
</div>
);
};
export default DeleteDialog;

I want to add edit button on my table and open the form on model when click demo modal button?

everyone, I want to add edit functionality into my project but I didn't understand how I can add that so can you please help me and I want to open my form on a modal on a button click "When they click on the button the modal will be open with the form" "when clicking on the edit button again modal will open with predefined values and when I edit the fields the table will be update "
here is my code
App.js
import React, { Component } from "react";
//import ReactDOM from "react-dom";
import Form from "./Form";
//import Modal from 'react-modal';
import { makeStyles } from '#material-ui/core/styles';
import Table from '#material-ui/core/Table';
import TableBody from '#material-ui/core/TableBody';
import TableCell from '#material-ui/core/TableCell';
import TableContainer from '#material-ui/core/TableContainer';
import TableHead from '#material-ui/core/TableHead';
import TableRow from '#material-ui/core/TableRow';
import Paper from '#material-ui/core/Paper';
import Button from '#material-ui/core/Button';
import "./styles.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
people: []
};
this.addPerson = this.addPerson.bind(this);
this.deletePerson = this.deletePerson.bind(this);
}
addPerson(name, email, phone) {
this.setState(prevState => ({
people: [...prevState.people, { name, email, phone }]
}));
}
componentDidMount() {
this.getPeople();
}
getPeople() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(response => this.setState({ people: response }))
.catch(error => console.log(error));
}
deletePerson(email) {
return () => {
this.setState(prevState => ({
people: prevState.people.filter(person => person.email !== email)
}));
};
}
editPerson(email) {
return () => {
this.setState({email})
}
}
render() {
console.log(this.state);
return (
<div className="App">
<Form addPerson={this.addPerson} />
<TableContainer component={Paper}>
<TableHead>
<TableRow>
<TableCell>LP</TableCell>
<TableCell>USER</TableCell>
<TableCell>EMAIL</TableCell>
<TableCell>Phone</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.people.map((person, index) => {
return (
<TableRow key={person.email}>
<TableCell>{index + 1}</TableCell>
<TableCell>{person.name}</TableCell>
<TableCell>{person.email}</TableCell>
<TableCell>{person.phone}</TableCell>
<TableCell>
<Button variant="contained" color="secondary" onClick={this.editPerson(person.email)}>
Edit
</Button>
</TableCell>
<TableCell>
<Button variant="contained" color="secondary" onClick={this.deletePerson(person.email)}>
Delete
</Button>
</TableCell>
</TableRow>
);
})}
</TableBody>
</TableContainer>
</div>
);
}
}
export default App;
Form.js
import React, { Component, useState } from "react";
import TextField from '#material-ui/core/TextField';
import Button from '#material-ui/core/Button';
import Modal from './Modal'
const validEmailRegex = RegExp(
/^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i
);
class Form extends Component {
constructor() {
super();
this.formSubmit = this.formSubmit.bind(this);
this.state = {
name: null,
email: null,
phone: null,
errors: {
name: '',
email: '',
phone: '',
}
};
}
handleChange = (event) => {
event.preventDefault();
const { name, value } = event.target;
let errors = this.state.errors;
switch (name) {
case 'name':
errors.name =
value.length < 5
? 'Name must be 5 characters long!'
: '';
break;
case 'email':
errors.email =
validEmailRegex.test(value)
? ''
: 'Email is not valid!';
break;
case 'phone':
errors.phone =
value.length < 8
? 'Password must be 8 characters long!'
: '';
break;
default:
break;
}
this.setState({ errors, [name]: value }, () => {
console.log(errors)
})
}
formSubmit(event) {
event.preventDefault();
const form = event.target;
const email = form.elements["email"].value;
const name = form.elements["name"].value;
const phone = form.elements["phone"].value;
this.props.addPerson(name, email, phone);
form.reset();
}
state = { show: false };
showModal = () => {
this.setState({ show: true });
};
hideModal = () => {
this.setState({ show: false });
};
render() {
return (
<div>
<Modal />
<form onSubmit={this.formSubmit}>
<TextField onChange={this.handleChange} id="name" type="text" defaultValue="" placeholder="Name..." />
<br />
<TextField onChange={this.handleChange} id="email" type="text" defaultValue="" placeholder="Email..." />
<br />
<TextField onChange={this.handleChange} id="phone" type="number" defaultValue="" placeholder="Phone Number" />
<br />
<br />
<Button type="submit" value="submit" variant="contained" color="primary" onSubmit={this.handleChange}> Submit </Button>
</form>
</div>
);
}
}
export default Form;
Modal.js
import React, { useState } from 'react';
import { Modal } from 'react-bootstrap';
import Button from '#material-ui/core/Button';
import TextField from '#material-ui/core/TextField';
function Example() {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<>
<Button variant="contained" color="primary" onClick={handleShow}>
Demo modal
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Body closeButton>
Form
</Modal.Body>
<Modal.Footer>
<Button variant="contained" color="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="contained" color="primary" onClick={handleClose}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</>
);
}
export default Example;
You want to open modal and the modal has a form inside it, right?
So you'll import Modal.js file in App.js
like that import Modal from ./Modal.js
And inside the initial state add
this.state = {
people: [],
showModal: false
};
Create a function to close model on press close button that inside Modal
const handleClose = () => this.setState({showModal: false})
And use the component under this line <div className="App">
you'll write:
<Modal show={this.state.showModal} email={this.state.email} close={this.handleClose}/>
Inside this function editPerson you must write this code without return
write:
this.setState({email, showModal: true})
ِAfter that you'll open Model.js file and import Form from Form.js file
and change this line
<Modal show={show} onHide={handleClose}>
to this:
<Modal show={props.show} onHide={props.handleClose}>
yeah and before I forget you should change this function (component)
function Example() to receive props so it'll be
function Example(props) {
...
}

Conditonal rendering REACT modal component

I have a view modal component (ViewModal.js)
import React from 'react'
import { Button, Modal } from 'react-bootstrap';
import './Modal.css';
class ViewModal extends React.Component {
constructor() {
super();
this.state = {
}
}
handleModalShowHide() {
this.setState({ showHide: !this.state.showHide })
}
render() {
return (
<div>
<Button variant="success" onClick={() => this.handleModalShowHide()}>
Write a review
</Button>
<Modal show={this.state.showHide}>
<Modal.Header closeButton onClick={() => this.handleModalShowHide()}>
<Modal.Title>Add your review</Modal.Title>
</Modal.Header>
<Modal.Body>
ModalBody
</Modal.Body>
<Modal.Footer>
<Button variant="outline-secondary" onClick={() => this.handleModalShowHide()}>
Close
</Button>
<Button variant="outline-success" onClick={() => this.handleModalShowHide()}>
Save Review
</Button>
</Modal.Footer>
</Modal>
</div>
)
}
}
export default ViewModal;
I import this in another functional component called viewcard.js
The logic of viewcard.js is as follows
import React from 'react';
import ViewModal from './ViewModal';
import Card from 'Card';
function handleClick(){
console.log('in handle');
}
const viewcard = () => {
return (
<p onClick={() => handleClick()}/>
Some text in paragraph
</p>
);
}
export default viewcard;
The Card component displays some text on the screen.
What I am trying to achieve is when a user clicks on that text, I want to show the modal.
Currently If I render the modal inside viewcard, by calling it, It will show a button based on this line of logic
<Button variant="success" onClick={() => this.handleModalShowHide()}>
Write a review
</Button>
I want to remove the button and have the same behaviour happen when the user clicks on the text in viewcard.js
ViewCard component:-
import React, {useState} from 'react';
import ViewModal from './ViewModal';
import Card from 'Card';
const ViewCard = () => {
const [showModal, setShowModal] = useState(false);
function handleClick(){
setShowModal(!showModal)
}
return (
<Card onClick={() => handleClick()}/>
{showModal && <ViewModal hideBtn={true} showModal={true} />}
);
}
export default ViewCard;
ViewModal Component:
import React from 'react'
import { Button, Modal } from 'react-bootstrap';
import './Modal.css';
class ViewModal extends React.Component {
constructor() {
super();
this.state = {
showHide: this.props.showModal ? true : false
}
}
handleModalShowHide() {
this.setState({ showHide: !this.state.showHide })
}
render() {
return (
<div>
{this.props.hideBtn ? null : <Button variant="success" onClick={() => this.handleModalShowHide()}>
Write a review
</Button>}
<Modal show={this.state.showHide}>
<Modal.Header closeButton onClick={() => this.handleModalShowHide()}>
<Modal.Title>Add your review</Modal.Title>
</Modal.Header>
<Modal.Body>
ModalBody
</Modal.Body>
<Modal.Footer>
<Button variant="outline-secondary" onClick={() => this.handleModalShowHide()}>
Close
</Button>
<Button variant="outline-success" onClick={() => this.handleModalShowHide()}>
Save Review
</Button>
</Modal.Footer>
</Modal>
</div>
)
}
}
export default ViewModal;
But you should always create a separate modal component.

Categories