Component Not Rendering React - Using Older React Router Dom Version - javascript

Hey guys using an older version of react-router-dom because I had to for this input form github i forked. Used to using useNavigate but this version is useHistory. I want to go from my main. dashboard to a page called House.js which renders a component MakePost.js. Whenever i travel to House its just a blank white screen. No errors. Help
Here is my Dashboard.js
async function House(){
return(history.push('/House'))
}
return (
<><>
<h2 className="title" style={{ left: "20%", marginTop: -150, marginLeft: 30 }}>Lestinsky Auctions.</h2>
</><>
<Card style={{ width: '400px', height: '500px', alignItems: 'center' }}>
<Card.Body>
<h2 className="text-center mb-4">Profile</h2>
{error && <Alert variant="danger">{error}</Alert>}
<strong>Email:</strong> {currentUser.email}
<Link to="/update-profile" className="btn btn-primary w-100 mt-3">
Update Profile
</Link>
<div>
<Button onClick={House} className="btn btn-primary w-100 mt-3">Go To Auction House</Button>
</div>
</Card.Body>
</Card>
<div style={{ left: '100%' }} className="w-100 text-center mt-2 btn btn-secondary">
<Link className="w-100 text-center mt-2 btn btn-secondary" variant="link" onClick={handleLogout}>
Log Out
</Link>
</div>
</></>
)
Here is my MakePost.js
import React, { useState} from 'react'
import { storage } from '../firebase'
import { ref, uploadBytes } from 'firebase/firebase-storage-compat'
import { v4 } from 'uuid'
function Upload(){
const [imageUpload, setImageUpload] = useState(null)
const uploadImage = () => {
if(imageUpload == null) return;
const imageRef = ref(storage, `images/${imageUpload.name + v4 }`)
uploadBytes(imageRef, imageUpload).then(() => {
alert("Image Uploaded")
})
}
return(
<div>
<input type="file" onChange={(event) => {setImageUpload(event.target.files)}}>
<button onClick={uploadImage}></button>
</input>
</div>
)
}
export default Upload
and here is my House.js
import MakePost from './MakePost'
function House(){
return(
<MakePost></MakePost>
)
}
export default House

Related

How do I close the modal window in react when clicking on the Add product button?

everyone. I can't write the code to close the modal window in React. I don't know how this can be done, I need that when clicking on the "Add" button, a modal window opens, the user enters the data, and clicking on the "Add product" button, the window closes immediately
Code:
import React from 'react';
import CatalogProducts from "./CatalogProducts";
import Info from "./Info";
import CreateProduct from "./CreateProduct";
import {Button} from 'react-bootstrap';
import Popup from 'reactjs-popup';
import 'reactjs-popup/dist/index.css';
import '../css/popup.css'
const Main = () => {
return (
<div>
<div className="d-flex justify-content-between" style={{ width: '33rem', margin: '10px' }}>
<Popup contentStyle={{width: "unset", backgroundColor: "red", border: "none", background: "none"}}
trigger={<Button> Add </Button>} modal>
<CreateProduct/>
</Popup>
<input placeholder={'search'}/>
<span>sort by</span>
<input/>
</div>
<CatalogProducts></CatalogProducts>
<Info></Info>
</div>
);
};
export default Main;
import React from 'react';
import {useDispatch} from "react-redux";
import {addProductAction} from "../action/productsAction";
import {ConfigProduct} from "../Utils/configProduct";
import '../css/popup.css'
import '../css/flex.css'
import {Button} from "react-bootstrap";
const CreateProduct = () => {
const dispatch = useDispatch()
const newProduct = new ConfigProduct()
function addProd() {
dispatch(addProductAction(newProduct))
}
return (
<div className = "popup">
<h2 style={{textAlign: "center", color: "red"}}>New product</h2>
<input className="item" placeholder="id" onChange={e => newProduct.idProd = e.target.value}/>
<input className="item" placeholder="info" onChange={e => newProduct.name = e.target.value}/>
<input className="item" placeholder="price" onChange={e => newProduct.infoProd = e.target.value}/>
<input className="item" placeholder="date" onChange={e => newProduct.price = e.target.value}/>
<input className="item" placeholder="enter url" onChange={e => newProduct.date = e.target.value}/>
<p>
<Button onClick={addProd}>Add product</Button>
</p>
</div>
);
};
export default CreateProduct;
I tried setting a flag to change the component class. but it didn't work out for me
In your main.js
[open, setOpen] = useState(false)
const closeModal = () => setOpen(false)
return (
<div>
<div className="d-flex justify-content-between" style={{ width: '33rem', margin: '10px' }}>
<Popup
contentStyle={
{width: "unset", backgroundColor: "red", border: "none", background: "none"}
}
trigger={<Button> Add </Button>}
modal
>
<CreateProduct closeModal={closeModal}/>
</Popup>
<input placeholder={'search'}/>
<span>sort by</span>
<input/>
</div>
<CatalogProducts></CatalogProducts>
<Info></Info>
</div>
)
and inside your CreateProduct.js
const CreateProduct = ({ closeModal }) => {
// your code
function addProd() {
dispatch(addProductAction(newProduct))
closeModal()
}
// rest of your code
)

React is only passing the last object in my array to a component

I have a react component where I map through a list of clients and display each client in a card.
return (
<div className='VolunteerClientsTab'>
{volunteerClients && volunteerClients.map((client) => (
<React.Fragment key={client.id}>
<div className='VolunteerClientsTab__card'>
<Avatar style={{ alignSelf: 'center', marginTop: '.5rem' }}>{client.first_name[0]}{client.last_name[0]}</Avatar>
<h2>{client.first_name} {client.last_name}</h2>
<h4>Details</h4>
<p><AiOutlineMail style={iconStyles} /> {client.email}</p>
<p><AiOutlinePhone style={iconStyles} /> {formatPhoneNumber(client.contact_number)}</p>
<h4 style={{ marginTop: '1rem' }}>Actions</h4>
<p onClick={handleOpenClientNeedsModal} className='hover-underline'><BiDonateHeart style={iconStyles} />View Needs</p>
<p className='hover-underline'><HiOutlineDocumentReport style={iconStyles} />Write Report</p>
<p className='hover-underline'><FiVideo style={iconStyles} />Contact Client</p>
</div>
<ClientNeeds open={openClientNeedsModal} handleClose={handleCloseClientNeedsModal} client={client} />
</React.Fragment>
))}
</div>
)
};
ClientNeeds is a component that renders an MUI modal to display additional client information. I am passing it the client object within the loop but when I open the modal only the client of the last index in the volunteerClients array was passed to all the modal components. Does anyone have any idea why this is happening?
ClientNeeds component
import React from 'react';
import Box from '#mui/material/Box';
import Modal from '#mui/material/Modal';
import PropTypes from 'prop-types';
const style = {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
bgcolor: 'background.paper',
border: '2px solid #000',
boxShadow: 24,
p: 4,
};
const ClientNeeds = ({ open, handleClose, client }) => {
return (
<div>
<Modal
open={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<h2>{client.email}</h2>
</Box>
</Modal>
</div>
)
};
ClientNeeds.propTypes = {
open: PropTypes.bool,
handleClose: PropTypes.func,
client: PropTypes.object
};
export default ClientNeeds;
MY SOLUTION
Passing the client onClick to an additional global state object and passing that state object to the modal,
const [selectedClient, setSelectedClient] = useState(null)
also only rendering the clientNeedsModal is there is an object in that state.
<div className='VolunteerClientsTab'>
{volunteerClients && volunteerClients.map((client) => (
<React.Fragment key={client.id}>
<div className='VolunteerClientsTab__card'>
<Avatar style={{ alignSelf: 'center', marginTop: '.5rem' }}>{client.first_name[0]}{client.last_name[0]}</Avatar>
<h2>{client.first_name} {client.last_name}</h2>
<h4>Details</h4>
<p><AiOutlineMail style={iconStyles} /> {client.email}</p>
<p><AiOutlinePhone style={iconStyles} /> {formatPhoneNumber(client.contact_number)}</p>
<h4 style={{ marginTop: '1rem' }}>Actions</h4>
<p onClick={() => handleOpenNeeds(client)} className='hover-underline'><BiDonateHeart style={iconStyles} />View Needs</p>
<p className='hover-underline'><HiOutlineDocumentReport style={iconStyles} />Write Report</p>
<p className='hover-underline'><FiVideo style={iconStyles} />Schedule Meeting</p>
</div>
{selectedClient ? (
<ClientNeeds open={openClientNeedsModal} handleClose={handleCloseClientNeedsModal} client={selectedClient} />
) : null}
</React.Fragment>
))}
</div>
const handleCloseClientNeedsModal = () => {
setSelectedClient(null)
setOpenClientNeedsModal(false);
}
const handleOpenNeeds = (client) => {
setSelectedClient(client)
handleOpenClientNeedsModal()
}
This allows me to pass any individual object within my array to the modal component as originally desired

Ant Design/antd calendar not working inside a modal

I am trying to use antD's calendar picker inside of a modal that has been created using Material-UI. When I put the datepicker inside of the modal component. It shows me the selection box but when I click on it, nothing opens to choose from. I tried wrapping it in a div as well, but that didn't work. Here's an image of the modal:
Modal code:
import React, { useState,useEffect } from "react";
import { withStyles } from "#material-ui/core/styles";
// import Button from "#material-ui/core/Button";
import Dialog from "#material-ui/core/Dialog";
import MuiDialogTitle from "#material-ui/core/DialogTitle";
import MuiDialogContent from "#material-ui/core/DialogContent";
import MuiDialogActions from "#material-ui/core/DialogActions";
import IconButton from "#material-ui/core/IconButton";
import CloseIcon from "#material-ui/icons/Close";
import Typography from "#material-ui/core/Typography";
import { Link } from "#material-ui/core";
import Table from "../Cards/CardTable";
import moment from "moment";
import CardLineChart from "components/Cards/CardLineChart.js";
import CardLineChart2 from "components/Cards/CardLineChart2.js";
import CardStats from "components/Cards/CardStats.js";
import { DatePicker, Space } from "antd";
const { RangePicker } = DatePicker;
const styles = (theme) => ({
root: {
width: 300,
margin: 0,
padding: theme.spacing(2),
},
closeButton: {
position: "absolute",
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500],
},
});
const DialogTitle = withStyles(styles)((props) => {
const { children, classes, onClose, ...other } = props;
return (
<MuiDialogTitle disableTypography className={classes.root} {...other}>
<Typography variant="h6">{children}</Typography>
{onClose ? (
<IconButton
aria-label="close"
className={classes.closeButton}
onClick={onClose}
>
<CloseIcon />
</IconButton>
) : null}
</MuiDialogTitle>
);
});
const DialogContent = withStyles((theme) => ({
root: {
// width: 200,
padding: theme.spacing(2),
},
}))(MuiDialogContent);
const DialogActions = withStyles((theme) => ({
root: {
margin: 0,
padding: theme.spacing(1),
},
}))(MuiDialogActions);
export default function CustomizedDialogs(props) {
const { name } = props;
console.log("Name is ======>", name)
const [open, setOpen] = useState(false);
const [colors, setColors] = useState(false);
const [deviceMsgs,setDeviceMsgs] = useState(null)
const [start, setStart] = useState();
const [end, setEnd] = useState();
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const onChange = (dates, dateStrings) => {
if (dateStrings.length > 0) {
setStart(dateStrings[0]);
setEnd(dateStrings[1]);
}
};
const DPicker = () => {
return (
<div>
<Space direction="vertical" size={12}>
<RangePicker
ranges={{
Today: [moment(), moment()],
"This Month": [
moment().startOf("month"),
moment().endOf("month"),
],
}}
onChange={onChange}
/>
</Space>
</div>
);
};
return (
<div>
<Link variant="outlined" color="primary" onClick={handleClickOpen}>
{name}
</Link>
<Dialog
maxWidth={"xl"}
// style={{ width: "100%" }}
onClose={handleClose}
aria-labelledby="customized-dialog-title"
open={open}
>
<DialogTitle
style={{ backgroundColor: colors ? "green" : "red" }}
id="customized-dialog-title"
onClose={handleClose}
>
{name}
</DialogTitle>
<DialogContent dividers>
<div>
<DPicker /> //////// Using the picker
<div className="relative w-full pr-4 max-w-full flex-grow flex-1">
<span className="font-semibold text-xl text-blueGray-700">
Last Update : 21 April 2021 17:00:00
</span>
</div>
<div className="m-4 px-4 md:px-10 mx-auto w-full">
<div>
{/* Card stats */}
<div className="flex flex-wrap">
<div className="w-full lg:w-6/12 xl:w-3/12 px-4">
<CardStats
statSubtitle="Total"
statTitle="10"
statArrow="up"
statPercent="3.48"
statPercentColor="text-emerald-500"
statDescripiron="Since last month"
statIconName="fas fa-percent"
statIconColor="bg-lightBlue-500"
/>
</div>
<div className="w-full lg:w-6/12 xl:w-3/12 px-4">
<CardStats
statSubtitle="ACTIVE"
statTitle="6"
statArrow="down"
statPercent="3.48"
statPercentColor="text-red-500"
statDescripiron="Since last week"
statIconName="fas fa-users"
statIconColor="bg-pink-500"
/>
</div>
<div className="w-full lg:w-6/12 xl:w-3/12 px-4">
<CardStats
statSubtitle="INACTIVE"
statTitle="4"
statArrow="down"
statPercent="1.10"
statPercentColor="text-orange-500"
statDescripiron="Since yesterday"
statIconName="far fa-chart-bar"
statIconColor="bg-red-500"
/>
</div>
<div className="w-full lg:w-6/12 xl:w-3/12 px-4">
<CardStats
statSubtitle="ALERT"
statTitle="--"
statArrow="up"
statPercent="12"
statPercentColor="text-emerald-500"
statDescripiron="Since last month"
statIconName="fas fa-chart-pie"
statIconColor="bg-orange-500"
/>
</div>
</div>
</div>
</div>
</Dialog>
</div>
);
}
Obviously, you should check my solution because it is just my assumption of your problem, but anyway it seems that it can help you:
<DatePicker
getPopupContainer={(triggerNode) => {
return triggerNode.parentNode;
}}
/>
By default, popup container is located nearby body but you can change it to your modal element. The my solution above covers that
I found a solution to the problem and it is straightforward.
after tinkering in the dev-tools, I found out that the Z-index of the antd Modal is set to 1055.
A simple override to the date-picker Z-index fixes the issue : I set it to 1056.
Its className is : ".ant-picker-dropdown"
.ant-picker-dropdown{
z-index: 1056;
}
solves the issue.
This will work.
Go to Node Module > antd > dist > antd.compact.css > change the z-index of elements accordingly.

Why does a useCallback option have to be called with a class component in Reactjs?

I am stumped. I have been trying to get a simple cleartext button to work. I have tried all the option available on this platform but nothing is working for me. React Hook useCallback cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook. I have no idea why this error is occurring. I am pretty new to react can anyone please help? I am trying to clear the text on a click of the clear button.
import React, { Component, useCallback, useState } from "react";
import {
Button,
Input,
Footer,
Card,
CardBody,
CardImage,
CardTitle,
CardText
} from "mdbreact";
import blankImg from "./blank.gif";
import "./style.css";
import "./flags.min.css";
import countriesList from "./countries.json";
class App extends Component {
state = {
search: ""
};
renderCountry = country => {
const { search } = this.state;
var code = country.code.toLowerCase();
const handleClick = useCallback(() => {
e.target.value = '';
}, []);
return (
<div className="col-md-3" style={{ marginTop: "20px" }}>
<Card>
<CardBody>
<p className="">
<img
src={blankImg}
className={"flag flag-" + code}
alt={country.name}
/>
</p>
<CardTitle title={country.name}>
{country.name.substring(0, 15)}
{country.name.length > 15 && "..."}
</CardTitle>
</CardBody>
</Card>
</div>
);
};
onchange = e => {
this.setState({ search: e.target.value });
};
render() {
const { search } = this.state;
const filteredCountries = countriesList.filter(country => {
return country.name.toLowerCase().indexOf(search.toLowerCase()) !== -1;
});
return (
<div className="flyout">
<main style={{ marginTop: "4rem" }}>
<div className="container">
<div className="row">
<div className="col">
<Input
label="Search Country"
icon="search"
onChange={this.onchange}
/>
<button onClick={handleClick}> Click to clear</button>
</div>
<div className="col" />
</div>
<div className="row">
{filteredCountries.map(country => {
return this.renderCountry(country);
})}
</div>
</div>
</main>
<Footer color="indigo">
<p className="footer-copyright mb-0">
© {new Date().getFullYear()} Copyright
</p>
</Footer>
</div>
);
}
}
export default App;
It is because you try to use hooks in a class based component. You can only use hooks like useCallback in functional components. Therefore you are mixing the concepts of object oriented and functional programming.
The following should do the trick:
import React, { Component, useCallback, useState } from "react";
import {
Button,
Input,
Footer,
Card,
CardBody,
CardImage,
CardTitle,
CardText
} from "mdbreact";
import blankImg from "./blank.gif";
import "./style.css";
import "./flags.min.css";
import countriesList from "./countries.json";
class App extends Component {
state = {
search: ""
};
const handleClick = (e) => {
e.target.value = '';
};
renderCountry = country => {
const { search } = this.state;
var code = country.code.toLowerCase();
return (
<div className="col-md-3" style={{ marginTop: "20px" }}>
<Card>
<CardBody>
<p className="">
<img
src={blankImg}
className={"flag flag-" + code}
alt={country.name}
/>
</p>
<CardTitle title={country.name}>
{country.name.substring(0, 15)}
{country.name.length > 15 && "..."}
</CardTitle>
</CardBody>
</Card>
</div>
);
};
onchange = e => {
this.setState({ search: e.target.value });
};
render() {
const { search } = this.state;
const filteredCountries = countriesList.filter(country => {
return country.name.toLowerCase().indexOf(search.toLowerCase()) !== -1;
});
return (
<div className="flyout">
<main style={{ marginTop: "4rem" }}>
<div className="container">
<div className="row">
<div className="col">
<Input
label="Search Country"
icon="search"
onChange={this.onchange}
/>
<button onClick={this.handleClick}> Click to clear</button>
</div>
<div className="col" />
</div>
<div className="row">
{filteredCountries.map(country => {
return this.renderCountry(country);
})}
</div>
</div>
</main>
<Footer color="indigo">
<p className="footer-copyright mb-0">
© {new Date().getFullYear()} Copyright
</p>
</Footer>
</div>
);
}
}
export default App;
useCallback hooks can only be used in functional components OR in a custom Hook NOT in class components.
You have declared your App component in class based approach i.e. Object oriented approach. To use useCallback hook for this, you should change your App component declaration to a functional component or Custom hook.
Something like this
function App() {
return (
<>Hello World!</>
);
}
you cannot useCallBack hook in class Component,we can do a simple thing to clear the button text, by using
a button text state, i.e. { btnTxt: "Clear ButtonText"} than update the state onclick
import React, { Component, useCallback, useState } from "react";
import {
Button,
Input,
Footer,
Card,
CardBody,
CardImage,
CardTitle,
CardText
} from "mdbreact";
import blankImg from "./blank.gif";
import "./style.css";
import "./flags.min.css";
import countriesList from "./countries.json";
class App extends Component {
state = {
search: "",
btnTxt: "Clear ButtonText"
};
renderCountry = country => {
const { search } = this.state;
var code = country.code.toLowerCase();
return (
<div className="col-md-3" style={{ marginTop: "20px" }}>
<Card>
<CardBody>
<p className="">
<img
src={blankImg}
className={"flag flag-" + code}
alt={country.name}
/>
</p>
<CardTitle title={country.name}>
{country.name.substring(0, 15)}
{country.name.length > 15 && "..."}
</CardTitle>
</CardBody>
</Card>
</div>
);
};
onchange = e => {
this.setState({ search: e.target.value });
};
render() {
const { search } = this.state;
const filteredCountries = countriesList.filter(country => {
return country.name.toLowerCase().indexOf(search.toLowerCase()) !== -1;
});
return (
<div className="flyout">
<main style={{ marginTop: "4rem" }}>
<div className="container">
<div className="row">
<div className="col">
<Input
label="Search Country"
icon="search"
onChange={this.onchange}
/>
<button onClick={()=> this.setState({btnText:""})}> {this.state.btnTExt}</button>
</div>
<div className="col" />
</div>
<div className="row">
{filteredCountries.map(country => {
return this.renderCountry(country);
})}
</div>
</div>
</main>
<Footer color="indigo">
<p className="footer-copyright mb-0">
© {new Date().getFullYear()} Copyright
</p>
</Footer>
</div>
);
}
}
export default App;

How to rerender the parent component by using the button in child component using react hooks

Parent Component Assessment.js
import Header from './Header'
import { Button, Dialog } from '#material-ui/core';
import Dialog1 from './Dialog1'
import {Modal, Button as ButtonBootstrap} from 'react-bootstrap';
const Assessment = () => {
const [show1, setShow1] = useState(false);
const handleClose1 = () => setShow1(false);
const handleShow1 = () => setShow1(true);
return (
<div>
<Dialog1 show1={show1} handleClose1={handleClose1} setShow1={setShow1}/>
<Header/>
<div className="d-flex flex-row">
<div className="d-flex flex-column align-items-start m-3 mx-5">
<div className='m-2 mx-5 visible' style={{borderRadius: "15px", padding: "10px",
paddingRight:"25px", backgroundColor:"#00CCFF"}}>
<h5 className='font-weight-bold'>Are you having any of these following:-</h5>
<div className='d-flex flex-row'>
<ul>
<li>Extremely difficult to breath</li>
<li>Severe Chest pain.</li>
<li>Having a tough time awakening</li>
<li>Losing consciousness</li>
</ul>
<Button onClick={handleShow1}
className="mx-5 my-4 align-content-around"
variant="contained"
style={{maxWidth: "30px", maxHeight: "30px"}}>
Yes
</Button>
</div>
</div>
</div>
</div>
</div>
)
}
export default Assessment
Child Component Dialog1.js
import React from 'react'
import {Modal, Button as ButtonBootstrap} from 'react-bootstrap';
import Stage1 from '../images/nurse level 0.png';
import Assessment from './Assessment';
const Dialog1 = ({show1, handleClose1, reload}) => {
function rerender() {
reload();
}
return (
<div>
<Modal show={show1} onHide={handleClose1}>
<Modal.Header closeButton>
<span className=" d-flex justify-content-center" style={{marginLeft: "150px"}}>
<img src={Stage1} class=" img-fluid d-block rounded " alt="nurse_image_1" style={{height: "165px"}}/>
</span>
</Modal.Header>
<Modal.Body className="conatainer-fluid m-auto">
<h4 className="font-weight-bold mx-3">
These symptoms are the sign of coronavirus.
Please call 9-1-1 or call the Emergency
Department for help!
</h4>
</Modal.Body>
<Modal.Footer className="d-flex justify-content-center mx-auto">
<ButtonBootstrap onClick={} variant="primary" size="lg" active> //want to rerender the parent component
Retake Self-Assessment
</ButtonBootstrap>
</Modal.Footer>
</Modal>
</div>
)
}
export default Dialog1
I have tried forceupdate() method but it didn't worked if someone can tell me better idea for this.
also i think history.goback will not be appropriate for this. I have tried to pass the method inside parent component to get called when the button inside child component is clicked.

Categories