Utilizing the "Ok" button in ANTd Modal in React - reactjs

I am creating a movie website that displays Modals of movies when you click on the movie card. I'm able to handle the "onCancel" which turns setActivateModal to false and closes the Modal, but I also want to allow the "Schedule" button to do something. The intended behavior is to have the "Schedule" button generate a different form in which I can fill out to "schedule" a movie with basic form entries that are then sent to my database. I'm not struggling with the form, but I'm struggling with how to handle generating one with the "Schedule" button. I'm unsure if you are allowed to do "nested" Modals, but any way it can be handled is fine.
import React, { useEffect, useState } from 'react';
import {
Layout,
Input,
Row,
Col,
Card,
Tag,
Spin,
Modal,
Typography,
Button,
} from 'antd';
import 'antd/dist/antd.css';
const { Content } = Layout;
const { Search } = Input;
const { Meta } = Card;
const TextTitle = Typography.Title;
const SearchBox = ({ searchHandler }) => {
return (
<Row>
<Col span={12} offset={6}>
<Search
placeholder="Search for movies to schedule!"
enterButton="Search"
size="large"
onSearch={value => searchHandler(value)}
/>
</Col>
</Row>
);
};
const MovieCard = ({
Title,
imdbID,
Poster,
ShowDetails,
DetailRequest,
ActivateModal,
}) => {
const clickHandler = () => {
ActivateModal(true);
DetailRequest(true);
fetch(`http://www.omdbapi.com/?i=${imdbID}&apikey=xxxxxxxx`)
.then(resp => resp)
.then(resp => resp.json())
.then(response => {
DetailRequest(false);
ShowDetails(response);
});
};
return (
<Col style={{ margin: '50px' }} span={3}>
<div>
<Card
style={{ width: 300 }}
cover={
<img
alt={Title}
src={
Poster === 'N/A'
? 'https://placehold.it/198x264&text=Image+Not+Found'
: Poster
}
/>
}
onClick={() => clickHandler()}
>
<Meta title={Title} />
</Card>
</div>
</Col>
);
};
const MovieDetail = ({
Title,
Actors,
Released,
Rated,
Runtime,
Genre,
Poster,
Plot,
}) => {
return (
<Row>
<Col span={11}>
<img
src={
Poster === 'N/A'
? 'https://placehold.it/198x264&text=Image+Not+Found'
: Poster
}
alt={Title}
/>
</Col>
<Col span={13}>
<Row>
<Col>
<TextTitle>{Title}</TextTitle>
</Col>
</Row>
<Row style={{ marginBottom: '.7em' }}>
<Col>{Actors}</Col>
</Row>
<Row style={{ marginBottom: '.7em' }}>
<Col>
<Tag>{Released}</Tag>
<Tag>{Rated}</Tag>
<Tag>{Runtime}</Tag>
<Tag>{Genre}</Tag>
</Col>
</Row>
<Row>
<Col>{Plot}</Col>
</Row>
</Col>
</Row>
);
};
const Loader = () => (
<div>
<Spin />
</div>
);
function Movies() {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [query, setQuery] = useState('');
const [activateModal, setActivateModal] = useState(false);
const [details, setShowDetails] = useState(false);
const [detailRequest, setDetailRequest] = useState(false);
useEffect(() => {
setError(null);
setData(null);
fetch(`http://www.omdbapi.com/?s=${query}&apikey=xxxxxxxx`)
.then(resp => resp)
.then(resp => resp.json())
.then(response => {
if (response.Response === 'False') {
setError(response.Error);
} else {
setData(response.Search);
}
})
.catch(({ message }) => {
setError(message);
});
}, [query]);
return (
<div className="Movies">
<Layout className="layout">
<Content>
<div style={{ background: '#4a576e', padding: 60, minHeight: 300 }}>
<SearchBox searchHandler={setQuery} />
<br />
<Row justify="center">
{data !== null &&
data.length > 0 &&
data.map((result, index) => (
<MovieCard
ShowDetails={setShowDetails}
DetailRequest={setDetailRequest}
ActivateModal={setActivateModal}
key={index}
{...result}
/>
))}
</Row>
</div>
<Modal
title="Details"
centered
visible={activateModal}
onCancel={() => setActivateModal(false)}
/* onOk= {() => What do I put here? */
width={800}
footer={[
<Button key="cancel" onClick={() => setActivateModal(false)}>
Cancel
</Button>,
<Button
key="schedule" /* onClick={() => setActivateForm(true)} */
>
Schedule
</Button>,
]}
>
{detailRequest === false ? (
<MovieDetail {...details} />
) : (
<Loader />
)}
</Modal>
</Content>
</Layout>
</div>
);
}
export default Movies;

Assuming all the routes are set up properly in your App.js, add the following changes:
Add this to your import list:
import { Link } from "react-router-dom";
In the Movies function, add the const [activeForm, setActiveForm] = useState(false); as shown below
function Movies() {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [query, setQuery] = useState('');
const [activateModal, setActivateModal] = useState(false);
const [details, setShowDetails] = useState(false);
const [detailRequest, setDetailRequest] = useState(false);
const [activateForm, setActivateForm] = useState(false);
In the return for your function, in the div tag right under the "Content" tag, add ActivateForm={setActivateForm} as shown below.
<div style={{ background: '#4a576e', padding: 60, minHeight: 300 }}>
<SearchBox searchHandler={setQuery} />
<br />
<Row justify="center">
{ data !== null && data.length > 0 && data.map((result, index) => (
<MovieCard
ShowDetails={setShowDetails}
DetailRequest={setDetailRequest}
ActivateModal={setActivateModal}
ActivateForm={setActivateForm}
key={index}
{...result}
/>
))}
</Row>
</div>
Finally, in the Modal tag, append to the "onOk" as such, and also in your Modal footer, add the following for "onClick".
<Modal
title='Details'
centered
visible={activateModal}
onCancel={() => setActivateModal(false)}
onOk={() => setActivateForm(true)}
width={800}
footer={[
<Button key="cancel" onClick={() => setActivateModal(false)}>
Cancel
</Button>,
<Button key="schedule" onClick={() =>setActivateForm(true)}><Link to='/ScheduleForm'>Schedule</Link ></Button>
]}
>
{ detailRequest === false ?
(<MovieDetail {...details} />) :
(<Loader />)
}
</Modal>

Related

hide buttons from interface

I have a modal, and this modal has two interfaces, the first is “QRReader” and the second is “PatientForm”, and the modal has two buttons, the first is “Approve” and the second is “Cancel”.
And I want to hide the two buttons within the interface of the "QRReader"
How can i solve the problem?
And this file contains the entire modal, knowing that the BasicModal tag is modal
import { Button, Col, Row } from "antd";
import {
useState
} from "react";
import { QrReader } from "react-qr-reader";
import patient from "../../../api/nuclearMedicineApi/services/Patient";
import { decrypt } from "../../../utils/decryption";
import PatientForm from "./form";
import { QrcodeOutlined } from '#ant-design/icons';
import BasicModal from "../modal";
import { FormattedMessage } from "react-intl";
import { notify } from "../notification";
const QRScanner = () => {
const [data, setData] = useState<number>(0);
const [patientInfoData, setPatientInfoData] = useState({})
const [modelVisible, setModelVisible] = useState<any>();
console.log('datadatadata: ', data)
const openNotificationWithIcon = () => {
// onSuccess: (data) => {
notify('success', 'ok', 'approve-message');
// },
};
return (
<>
<QrcodeOutlined
className='cursor-pointer'
style={{ fontSize: '2rem' }}
color={'#fff'}
onClick={(e) => {
e.stopPropagation()
setModelVisible(true)
}}
/>
<BasicModal
header={<>
<h2 className='text-primary'><FormattedMessage id="qr-scanner" /></h2>
</>}
content={
<>
{
data !=0 ?
<PatientForm patientInfoData={patientInfoData} data={data} />
:
<Row>
<Col span={18} offset={3}>
<QrReader
onResult={async (result: any, error) => {
if (!!result) {
const t = result?.text;
const d = decrypt(t);
let zz: any = d.match(/(\d+)/)
Math.floor(zz[0])
setData(zz[0]);
const pationInfo = await patient.patientGet({ Id: Number(zz[0]) })
setPatientInfoData(pationInfo)
}
if (!!error) {
console.info(error);
}
}} // style={{ width: '100%' }}
constraints={{ facingMode: 'user' }}
// style={{ width: '100%' }}
/>
</Col>
</Row>
}
<Row>
<Col span={1} offset={3}>
<Button
type='primary'
className='savebtn'
onClick={() => {
patient.switchToPresent(data || 0)
openNotificationWithIcon()
}}
>
<FormattedMessage id={'approve'} />
</Button>
</Col>
<Col span={8} offset={4}>
<Button
type='default'
className='savebtn'
onClick={() => {
setModelVisible(false);
setData(0);
}}
>
<FormattedMessage id={'cancel'} />
</Button>
</Col>
</Row>
</>
}
isOpen={modelVisible}
footer={false}
width='50vw'
handleCancel={() => {
setModelVisible(false);
}}
afterClose={
() => setData(0)
}
/>
</>
)
};
export default QRScanner;
I think you should be able to use a similar condition as you are using to determine if you should render patientForm vs QRReader. You could wrap your buttons with something like this
{ data = 0 && (
<Row>
<Col span={1} offset={3}>
<Button
type='primary'
className='savebtn'
onClick={() => {
patient.switchToPresent(data || 0)
openNotificationWithIcon()
}}
>
<FormattedMessage id={'approve'} />
</Button>
</Col>
<Col span={8} offset={4}>
<Button
type='default'
className='savebtn'
onClick={() => {
setModelVisible(false);
setData(0);
}}
>
<FormattedMessage id={'cancel'} />
</Button>
</Col>
</Row>
)
}
You can have the same condition for showing the buttons which you have for QRScanner and PatientForm
{data != 0 ? (
<Row>
<Col span={1} offset={3}>
<Button
type='primary'
className='savebtn'
onClick={() => {
patient.switchToPresent(data || 0)
openNotificationWithIcon()
}}
>
<FormattedMessage id={'approve'} />
</Button>
</Col>
<Col span={8} offset={4}>
<Button
type='default'
className='savebtn'
onClick={() => {
setModelVisible(false);
setData(0);
}}
>
<FormattedMessage id={'cancel'} />
</Button>
</Col>
</Row>
) : </>}

How to create different hashtags for different NFTs

In the process of creating an NFT MarketPlace, I want to be able to write a hashtag for each NFT.
I tried to make this function. When the button(Tooltips) is clicked, the Modal screen is displayed so that you can enter a hashtag, and the entered hashtag is displayed under the NFT image.
However, when writing to one NFT, the same character is output to all NFTs.
*I am using a server with Moralis.
I tried to find a way, but I couldn't solve it.
This is my code.
const [visible1, setVisibility1] = useState(false);
const [nftToSend1, setNftToSend1] = useState(null);
const [tagItem, setTagItem] = useState('')
const [tagList, setTagList] = useState([])
const onKeyPress = e => {
if (e.target.value.length !== 0 && e.key === 'Enter') {
submitTagItem()
}
}
const submitTagItem = () => {
let updatedTagList = [...tagList]
updatedTagList.push(tagItem)
setTagList(updatedTagList)
setTagItem('')
}
const deleteTagItem = e => {
const deleteTagItem = e.target.parentElement.firstChild.innerText
const filteredTagList = tagList.filter(tagItem => tagItem !== deleteTagItem)
setTagList(filteredTagList)
}
return (
<> ...
<div style={styles.NFTs}>
{NFTBalance &&
NFTBalance.map((nft, index) => (
<Card
hoverable
actions={[
<Tooltip title="HashTag">
<TagOutlined onClick={() => handleTagClick(nft)} />
</Tooltip>,
]}
cover={
<Image
preview={false}
src={nft?.image || "error"}
fallback="data:image/png;base64,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"
alt=""
style={{ height: "240px" }}
/>
}
key={index}
>
<Meta title={nft.name} description={nft.contract_type} />
{tagList.map((value, index) => (
<p>#{value}</p> //hashtag(output)
))}
</Card>
))}
</div>
<Modal
title={`HashTag ${nftToSend1?.name} #${nftToSend1?.token_id}`}
visible={visible1}
onCancel={() => setVisibility1(false)}
footer={[
<Button onClick={() => setVisibility1(false)}>
Save
</Button>,
]}
>
<Spin spinning={loading}>
<img
src={`${nftToSend1?.image}`}
/>
<Input
autoFocus
placeholder="Press Enter to enter a hashtag"
tabIndex={2}
onChange={(e) => setTagItem(e.target.value)}
onKeyPress={onKeyPress}
value={tagItem}
/>
{tagList.map((tagItem, index) => {
return (
<div key={index}>
<text>{tagItem}</text>
<button onClick={deleteTagItem}>X</button>
</div>
)
})}
</Spin>
</Modal>
...

useState not updating data when passing from parent function component using ref

I am trying to send data to child function component where I am binding form fields with that data. It works fine on first call, but when I am calling 2nd time the data never update in state, its always shows the first one.
This is parent which use the ref of child component
export default function Form1() {
const [count, setCount] = useState(0);
const [counter, setCounter] = useState(10);
const AddNewRef = useRef();
const clickMe=() => {
setCount(count+1);
setCounter(counter*2);
AddNewRef.current.showDrawer(counter*2);
}
return (
<div>
<p>You clicked count: {count} & counter: {counter} times</p>
{
count > 10 ?
(
<p className='red'>your count is greater then 10</p>
) :
(
<p className='green'>your count is less then 10</p>
)
}
<button onClick={() => clickMe()}>
Click me
</button>
<AddNew ref={AddNewRef} Count={count} Counter={counter} />
</div>
)
}
This is child component
const AddNew=forwardRef((props, ref) => {
const[objCounter, setobjCounter] = useState(null);
useImperativeHandle(
ref,
() => ({
showDrawer(count) {
setobjCounter(count);
//only shows at first click at parent, Not updating on 2nd, 3rd click from parent and so on....
}
}),
)
return (
<>
<Drawer
title={<span> <i className='fa-solid fa-kaaba' /> Haj Setup Form</span>}
width={window.innerWidth > 900 ? 800 : window.innerWidth - 50}
onClose={onClose}
visible={visible}
bodyStyle={{ paddingBottom: 80 }}
extra={
<Space>
<Button onClick={onClose}>Cancel</Button>
<Button onClick={onClose} type="primary">
Submit
</Button>
</Space>
}
>
<Form
style={{display: formVisible ? 'block' : 'none'}}
form={form}
layout="vertical"
onFinish={onFinish}
onFinishFailed={onFinishFailed}
autoComplete="off"
hideRequiredMark>
<Row gutter={16}>
<Col xs={24} sm={24} md={24} lg={24}>
<Form.Item
name="packageName"
label="Package Name"
rules={[{ required: true, message: 'Please enter package name' }]}
initialValue={objCounter}
>
<Input style={{width: '100%'}}
maxLength={100} />
</Form.Item>
</Col>
</Row>
</Form>
</Drawer>
</>
)
});
export default AddNew
Since the state updates are working and you are simply wanting to update the form field, you can use the returned form reference from the useForm hook to update the form state. In this case, update the packageName field.
const AddNew = forwardRef((props, ref) => {
const [objCounter, setobjCounter] = useState(13);
const [visible, setVisible] = useState(false);
const [formVisible, setformVisible] = useState(true);
const [form] = Form.useForm();
useImperativeHandle(ref, () => ({
showDrawer(count) {
setobjCounter(count);
setVisible(true);
form.setFieldsValue({
packageName: count // <-- update the specific field
});
}
}));
const onClose = () => {
setVisible(false);
};
return (
...
);
});

Removing complex components from an array in ReactJS

I'm trying to make a list of components. I need to remove the items individually but it seems that the state inside the remove function is always outdated.
For example, if I add 10 authors and click in the 10th author remove button, it'll show me 9 elements (which is already wrong) and if I click on the 2nd author, it shows me just 1 element inside the array. Am I missing something here?
const [authorsFields, setAuthorsFields] = useState<Array<JSX.Element>>([]);
const removeAuthorField = () => {
console.log(authorsFields.length);
}
const removeButton = () => {
return (
<Col className={"d-flex justify-content-end py-1"}>
<Button variant={"danger"} onClick={() => removeAuthorField()}>Remove author</Button>
</Col>
);
}
const authorField = (removable: boolean) => {
return (
<>
<Row className={"mb-2"}>
<Form.Group className={"py-1"}>
<Form.Label>Author name</Form.Label>
<Form.Control type={"text"}/>
</Form.Group>
{removable && removeButton()}
</Row>
</>
);
}
const addAuthorField = () => {
if (authorsFields.length !== 0) {
setAuthorsFields((old) => [...old, authorField(true)]);
} else {
setAuthorsFields([authorField(false)]);
}
}
useEffect(() => {
if (authorsFields.length === 0) {
addAuthorField();
}
}, [])
return (
<>
<Col sm={3} style={{maxHeight: "60vh"}} className={"mt-4"}>
<Row>
{authorsFields}
<Row>
<Form.Group className={"py-1"}>
<Button style={{width: "100%"}} onClick={() => addAuthorField()}>
Add Author
</Button>
</Form.Group>
</Row>
</Row>
</Col>
</>
);
Use the following functional component as an example to modify your code on how to use JSX elements seperated from the state management inside the functional components.
import React, { useState } from "react";
import { Button, Row, Col } from "antd";
function App() {
const [authorsCount, setAuthorsCount] = useState(0);
// Use authorsFields to manage authors details in an array of objects
const [authorsFields, setAuthorsFields] = useState([]);
const removeAuthorField = (id) => {
// To remove relevant author filter out the authors without the relevant id
setAuthorsFields((old) =>
old.filter((authorField) => authorField.id !== id)
);
};
const addAuthorField = () => {
setAuthorsFields((old) => [...old, { id: authorsCount, removable: true }]);
setAuthorsCount((old) => old + 1);
};
return (
<div>
<Col sm={3} style={{ maxHeight: "60vh" }} className={"mt-4"}>
<Row>
{authorsFields.map((authorField) => (
<Row className={"mb-2"}>
<div className={"py-1"}>
<div>{`Author name ${authorField.id}`}</div>
</div>
{authorField.removable && (
<>
<Col className={"d-flex justify-content-end py-1"}>
<Button
variant={"danger"}
onClick={() => removeAuthorField(authorField.id)}
>
Remove author
</Button>
</Col>
</>
)}
</Row>
))}
<Row>
<div className={"py-1"}>
<Button
style={{ width: "100%" }}
onClick={() => addAuthorField()}
>
Add Author
</Button>
</div>
</Row>
</Row>
</Col>
</div>
);
}
export default App;
Following is the view.

Create search box in the list in react js component

Please tell, how to carry out search in the list of components which code is specified below correctly?
The search should be performed by title or full description of the list item.
Component with list of Item components:
const PathItems = () => {
const dispatch = useDispatch();
const pathDescription = useSelector(state => state.firestore.ordered.pathDescription);
const handleClick = (path) => {
dispatch(selectPath(path));
}
if(pathDescription && pathDescription.length !== 0){
return (
<React.Fragment>
<Row>
<Col className="pl-0 border-right border-dark">
{pathDescription && pathDescription.map(item => (
<PathItem
key={item.id}
item={item}
onInfoChange={ handleClick }
/>
))}
</Col>
<Col>
<FullDecript/>
</Col>
</Row>
</React.Fragment>
)
} else {
return (
<h5 className="text-muted text-center text-middle">Add your first route</h5>
)
}
}
export default compose(firestoreConnect(()=> ['pathDescription']))(PathItems);
Item component code:
const PathItem = ({ item, onInfoChange }) => {
const handleClick = () => {
onInfoChange(item);
}
return (
<React.Fragment>
<Card as="a"
style={{cursor: 'pointer'}}
className={'mb-2'}
onClick={ handleClick }>
<Card.Body>
<Row className="align-items-center">
<Col xs={1}>
</Col>
<Col xs={7}>
<h5>{item.title}</h5>
{item.sDescript}
</Col>
<Col xs={4} className="text-right">
<label>{item.length}600 km</label>
</Col>
</Row>
</Card.Body>
</Card>
</React.Fragment>
);
}
export default PathItem;
General view of the described components
Thanks in advance)
...
const [searchQuery, setQuery] = useState("");
const inputEvent = (event) => {
const data = event.target.value;
console.log(pathDescription);
setQuery(data);
}
const filterItems = pathDescription && pathDescription.filter(item => {
return item.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
item.fDescript.toLowerCase().includes(searchQuery.toLowerCase());
})
...
<Col className="pl-0 border-right border-dark" style={divStyle}>
<InputGroup className="mb-3">
<FormControl
type="text"
placeholder="Type..."
aria-describedby="basic-addon2"
value={ searchQuery }
onChange={ inputEvent }
/>
<InputGroup.Append>
<Button variant="outline-secondary">
<img
alt="Logo"
src="https://cdn1.iconfinder.com/data/icons/app-user-interface-line/64/search_focus_user_interface_app_zoom-256.png"
width="25"
height="25"
className="d-inline-block align-top"/>
</Button>
</InputGroup.Append>
</InputGroup>
{filterItems.sort((a, b) => b.favorite - a.favorite).map(item => (
<PathItem
key={item.id}
item={item}
onInfoChange={ handleClick }
/>
))}
</Col>

Resources