It randomly started doing this and I am not sure why tho. I have two modals (these are named differently) that are exactly the same but only one is working. The modal I am using is the React-Modal library. The first one works just fine on the home page but the second doesn't at all on an edit details page.
What I did notice is that there is a div placed with an Id of __Next on the home page that is working that places the content of the modal inside but that same exact div does not show up on the other page for the same modal to work.
Below are the two components I am working with and its parent component that houses both
Parent:
import styles from './homeheader.module.css';
import { useRouter } from 'next/router';
import { useState } from 'react';
import NewInvoice from '../invoice/modal/NewInvoice';
import Link from 'next/link';
import { getDatabase, ref, remove } from "firebase/database";
import { database } from '../firebase/firebase';
import EditInvoice from '../invoice/modal/EditInvoice';
export default function HomeHeader(props) {
const [newInvoiceModalIsOpen, setNewInvoiceOpen] = useState(false);
const [editInvoiceModalIsOpen, setEditInvoiceOpen] = useState(false);
const router = useRouter();
const pathName = router.pathname;
const { data, count, id, detail } = props;
function openNewInvoiceModalHandler() {
setNewInvoiceOpen(true)
}
function closeNewInvoiceModalHandler() {
setNewInvoiceOpen(false)
}
function openEditInvoiceModalHandler() {
setEditInvoiceOpen(true)
}
function closeEditInvoiceModalHandler() {
console.log(data)
setEditInvoiceOpen(false)
}
function deleteInvoiceHandler() {
console.log('delete')
console.log(id)
const db = database;
remove(ref(db, 'invoices/' + id))
}
function markAsPaidInvoiceHandler() {
console.log('paid')
}
if (pathName === '/detail/[id]') {
return (
<>
<div className={styles.headerwrapper}>
<Link href="/">
<a>Go back</a>
</Link>
{/* <p>{detail.data.status}</p> */}
<div>
<button onClick={openEditInvoiceModalHandler}>Edit</button>
<button onClick={deleteInvoiceHandler}>Delete</button>
<button onClick={markAsPaidInvoiceHandler}>Mark as Paid</button>
</div>
</div>
<EditInvoice isOpen={editInvoiceModalIsOpen} closeModal={closeEditInvoiceModalHandler} details={detail}/>
</>
)
}
return (
<div className={styles.headerwrapper}>
<div className={styles.leftside}>
<h1 className={styles.header}>Invoices</h1>
<p className={styles.text}>There are {count} total invoices</p>
</div>
<div className="right-side">
<select className={styles.filter} id="filter" placeholder="Filter by status">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<button className={styles.button} onClick={openNewInvoiceModalHandler}>New Invoice</button>
</div>
<NewInvoice isOpen={newInvoiceModalIsOpen} closeModal={closeNewInvoiceModalHandler} count={count}/>
</div>
)
}
Child modal component that IS WORKING:
import { useForm } from 'react-hook-form';
import ReactModal from 'react-modal';
import { database } from '../../firebase/firebase';
import { ref, set } from "firebase/database";
import styles from './newinvoice.module.css'
// ReactModal.setAppElement("#__next")
export default function NewInvoice (props) {
const { register, handleSubmit, watch, formState: { errors } } = useForm();
function onSubmit(data) {
const randGen = Math.floor(Math.random() * 9999999);
data.id = randGen;
const db = database;
set(ref(db, '/invoices/' + randGen), {
data: data
})
setTimeout(() => {
window.location.reload(true)
}, 500)
props.closeModal();
}
return (
<>
<ReactModal isOpen={props.isOpen}>
<h1>New Invoice</h1>
<form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
<label>Street Address</label>
<input {...register("senderAddress.street")} />
<label>City</label>
<input {...register("senderAddress.city")} />
<label>Postal Code</label>
<input {...register("senderAddress.postCode")} />
<label>Country</label>
<input {...register("senderAddress.country")} />
<label>Client"s Name</label>
<input {...register("clientName")} />
<label>Client"s Email</label>
<input {...register("clientEmail")} />
<label>Street Address</label>
<input {...register("clientAddress.street")} />
<label>City</label>
<input {...register("clientAddress.city")} />
<label>Postal Code</label>
<input {...register("clientAddress.postCode")} />
<label>Country</label>
<input {...register("clientAddress.country")} />
<label>Invoice Date</label>
<input {...register("createdAt")} />
<label>Payment Terms</label>
<input {...register("paymentTerms")} />
<label>Project Description</label>
<input {...register("description")} />
{/* //Item list goes here */}
<input {...register("items")} />
<input type="submit" placeholder="Submit"/>
</form>
<button onClick={props.closeModal}>Close</button>
</ReactModal>
</>
)
}
Child component that is NOT WORKING:
import { useForm } from 'react-hook-form';
import ReactModal from 'react-modal';
import { database } from '../../firebase/firebase';
import { ref, set } from "firebase/database";
import { useRouter } from 'next/router';
import styles from './newinvoice.module.css'
import { useEffect, useState } from 'react';
ReactModal.setAppElement("#react-modals")
export default function EditInvoice(props) {
const { register, handleSubmit, watch, formState: { errors } } = useForm();
const [formData, setFormData] = useState();
const { isOpen, closeModal, detail } = props;
const router = useRouter();
const id = router.query.id;
const dbLink = `https://invoice-app-3fa85-default-rtdb.firebaseio.com/invoices/${id}.json`;
function onSubmit(data) {
const db = database;
set(ref(db, '/invoices/' + id), {
data: data
})
setTimeout(() => {
window.location.reload(true)
}, 500)
props.closeModal();
}
// function onSubmit(data) {
// console.log(data)
// }
useEffect(() => {
// fectchData();
console.log(formData)
})
const fectchData = async () => {
try {
const res = await fetch(dbLink);
const json = await res.json();
setFormData(json)
} catch (error) {
console.log(error)
}
}
if (!formData) {
console.log('not working')
return <p>Loading....</p>
}
return (
<>
<ReactModal isOpen={true} portalClassName="editInvoiceModal" parentSelector={() => document.querySelector('#react-modals')}>
<h1>Edit Invoice </h1>
<form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
<label>Street Address</label>
<input {...register("senderAddress.street")} defaultValue={detail.senderAddress.street}/>
{/* <label>City</label>
<input {...register("senderAddress.city")} defaultValue={formData.senderAddress.city}/>
<label>Postal Code</label>
<input {...register("senderAddress.postCode")} defaultValue={formData.senderAddress.postCode}/>
<label>Country</label>
<input {...register("senderAddress.country")} defaultValue={formData.senderAddress.country}/>
<label>Client"s Name</label>
<input {...register("clientName")} defaultValue={formData.clientName}/>
<label>Client"s Email</label>
<input {...register("clientEmail")} defaultValue={formData.clientEmail}/>
<label>Street Address</label>
<input {...register("clientAddress.street")} defaultValue={formData.clientAddress.street}/>
<label>City</label>
<input {...register("clientAddress.city")} defaultValue={formData.clientAddress.city}/>
<label>Postal Code</label>
<input {...register("clientAddress.postCode")} defaultValue={formData.clientAddress.postCode}/>
<label>Country</label>
<input {...register("clientAddress.country")} defaultValue={formData.clientAddress.country}/>
<label>Invoice Date</label>
<input {...register("createdAt")} defaultValue={formData.createdAt}/>
<label>Payment Terms</label>
<input {...register("paymentTerms")} defaultValue={formData.paymentTerms}/>
<label>Project Description</label>
<input {...register("description")} defaultValue={formData.description}/>
{/* //Item list goes here */}
<input type="submit" placeholder="Submit"/>
</form>
<button onClick={closeModal}>Close</button>
</ReactModal>
</>
)
}
It may be sloppy code as of now and was working to clean it up a lot more until I noticed this issue.
In your parent, try adding a placeholder.
<div id="react-modals" />
Your react modal seems to be looking for a div with the #react-modals id.
Related
I've recently started maintaining JavaScript code and now i am facing trouble in the returning function in line 39. Can someone please help? I have checked the syntax and can't find anything wrong................................................................???????????????????????????????????????????????????????????????????????
import React, { useState, useEffect} from "react";
import axios from "axios";
import { renderMatches, useNavigate, useParams, } from "react-router-dom";
const Editorg = () => {
let navigate = useNavigate();
const {id} = useParams();
console.log(id);
const [user, setUser] = useState ({
name:"",
poname:"",
type:"",
ostatus:"",
});
const { name, poname, type, ostatus } = user;
const onInputChange = e => {
setUser({...user, [e.target.name]: e.target.value });
};
useEffect(() => {
loadUser();
}, []);
};
const onSubmit = async e => {
e.preventDefault();
await axios.put( 'http://localhost:3001/users/${id}' , user);
navigate.push("/");
};
const loadUser = async () =>{
const result = await axios.get('http://localhost:3001/users/${id}', user);
setUser(result.data);
};
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5">
<h5 className="text-left mb-4"> Edit Organization </h5>
<form onSubmit={e => onSubmit(e)}>
<div className="form-group">
<label> Organization Name </label>
<input type="text" className="form-control" name="name" value={name}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<label> Parent Organization Name </label>
<input type="text" className="form-control" name="poname" value={poname}
onChange={e => onInputChange(e)}
/>
</div>
<div className="form-group">
<label> Type </label>
<input type="text" className="form-control" name="type" value={type}
onChange={e => onInputChange(e)}
/></div>
<div className="form-group">
<label> Organization Status </label>
<input type="text" className="form-control" name="ostatus" value={ostatus}
onChange={e => onInputChange(e)}
/></div>
<div className="container">
<div className="btn-6">
<button className="btn btn-danger float-right">Update</button>
</div>
</div>
</form>
</div>
</div>
);
}
Around line 26 you are closing the function too early.
useEffect(() => {
loadUser();
}, []);
}; // <- Move this to the very end
const onSubmit = async e => {
</div>
</div>
);
}; // <- Move to here
You mistakly add extra termination of curly bracket
useEffect(() => {
loadUser();
}, []);
}; // <--- remove this
Hello guys so i tried to make global state so the other page can use the state. The problem is i got an error that says:
Login.js:18 Uncaught TypeError: Cannot destructure property 'emailLog' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is undefined.
Im doing this because i want the email from user after logged in and pass them to another page so that i can display the logged in user.
App.js:
export const EmailUser = React.createContext();
function App() {
Axios.defaults.withCredentials = true;
const [invoice, setInvoice] = useState("");
const [currency, setCurrency] = useState("IDR");
const [myFile, setMyFile] = useState("");
const [emailLog, setEmailLog] = useState("");
return (
<EmailUser.Provider value={{ emailLog, setEmailLog }}>
<div className="App">
<BasicExample />
<div className="formInput">
<form method="POST" encType="multipart/form-data" action="http://localhost:3001/upload">
<div className="textUser"></div>
<input
className="inputForm"
defaultValue={emailLog}
type="email"
disabled
name="email"
/>
<input className="inputForm" type="number" placeholder="Invoice No" name="InvoiceNo" />
<input className="inputForm" type="date" name="Invoice_Date" />
<input className="inputForm" type="text" placeholder="Description" name="Description" />
<select
className="selectBox"
name="Currency"
onChange={(e) => {
setCurrency(e.target.value);
}}
>
<option value="IDR">IDR</option>
<option value="USD">USD</option>
<option value="YEN">YEN</option>
</select>
<input className="inputForm" type="number" placeholder="Amount" name="Amount" />
<input
className="custom-file-upload"
multiple
type="file"
name="DocumentFile"
onChange={(e) => {
setMyFile(e.target.value);
}}
/>
<button className="btnSubmit">Submit</button>
</form>
</div>
</div>
</EmailUser.Provider>
);
}
export default App;
Login.js
const Login = () => {
let navigate = useNavigate();
const { emailLog, setEmailLog } = useContext(EmailUser);
const [passwordLog, setPasswordLog] = useState("");
const [loginStatus, setLoginStatus] = useState("");
Axios.defaults.withCredentials = true;
const login = (e) => {
e.preventDefault();
Axios.post("http://localhost:3001/login", {
email: emailLog,
password: passwordLog,
}).then((response) => {
console.log(response);
if (response.data.message) {
alert(response.data.message);
} else {
setLoginStatus(response.data[0].email);
alert("Redirecting");
navigate("/home");
}
});
};
console.log(emailLog);
useEffect(() => {
Axios.get("http://localhost:3001/login").then((response) => {
if (response.data.loggedIn == true) {
setLoginStatus(response.data.email[0].email);
}
});
});
return (
<div>
<img className="wave" src={Wave} />
<img className="wave2" src={WaveV2} />
<div className="wrapper">
<div className="img">{/* <img src={Background}/> */}</div>
<div className="register-content">
<div className="registerForm">
<img src={Avatar} />
<h2 className="title">Welcome</h2>
<div className="input-div one">
<div className="i">
<i className="fas fa-user">
<GrMail />
</i>
</div>
<div className="div">
<input
type="email"
className="input"
placeholder="Email"
required
onChange={(e) => {
setEmailLog(e.target.value);
}}
/>
</div>
</div>
<div className="input-div pass">
<div className="i">
<i className="fas fa-lock">
<AiFillLock />
</i>
</div>
<div className="div">
<input
type="password"
className="input"
placeholder="Password"
required
onChange={(e) => {
setPasswordLog(e.target.value);
}}
/>
</div>
</div>
Don't have an account ?
<button type="submit" className="btn" onClick={login}>
Login
</button>
</div>
</div>
</div>
</div>
);
};
export default Login;
EmailUser context works only with the components that are children of EmailUser.Provider, and it doesn't seem to be the case for Login component. An easy way is to create a separate component, in some EmailUserProvider.js, like so:
import {createContext, useState} from "react"
export const EmailUser = createContext();
export default function EmailUserProvider({children}) {
const [emailLog, setEmailLog] = useState("");
return (
<EmailUser.Provider value={{ emailLog, setEmailLog }}>
{children}
</EmailUser.Provider>
);
}
And make it wrap all the components that would consume it. If I assume all my components and routes are rendered in App and want the context to be global, I would do so:
<EmailUserProvider>
<App/>
</EmailUserProvider>
Simple input form on the home page linking into what is supposed to be a profile page. However I am having the two problems mentioned above. I have included the code below to see what people think. I don't understand why as soon as the array moves over to /profile it disappears. And why often the page doesn't even connect to /profile.
I have only a couple of months experience so need some expert advise regarding what the problem is. What is the problem in your opinion?
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min';
import Home from './Home.js'
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'
const Profile = ({loading, setLoading, submitForm, setSubmitForm}) => {
useEffect (() => {
setInterval(() => {
setLoading(false)
}, 3000);
}, []);
return (<>
{loading && (<div class="loading"><i class="fa fa-spinner fa-spin"></i>
<div>Loading</div></div>)}
{!loading && (
<div class="main">
<div class="profile col-10"><div class="imageDiv">
<img class="image" src={require("./R (1).png")} alt="person"></img>
</div>
</div>
</div>
)}
</>)
}
function App() {
const [firstName, setFirstName] = useState('');
const [secondName, setSecondName] = useState('');
const [submitForm, setSubmitForm] = useState([]);
const [ageMin, setAgeMin] = useState(18);
const [ageMax, setAgeMax] = useState(80);
const [selectOne, setSelectOne] = useState('Man')
const [selectTwo, setSelectTwo] = useState('Woman')
const [loading, setLoading]= useState(true)
return (
<Router>
<div className="App">
<Routes>
<Route path="/" element={<Home selectOne={selectOne} setSelectOne={setSelectOne} selectTwo={selectTwo} setSelectTwo={setSelectTwo} firstName={firstName} setFirstName={setFirstName} secondName={secondName} setSecondName={setSecondName} ageMin={ageMin} setAgeMin={setAgeMin} ageMax={ageMax} setAgeMax={setAgeMax} submitForm={submitForm} setSubmitForm={setSubmitForm}/>}></Route>
<Route path="/Profile" element={<Profile loading={loading} setLoading={setLoading}/>}></Route>
</Routes>
</div>
</Router>
);
}
export default App; ```
```import React, {useState} from 'react';
import { Link } from 'react-router-dom';
function Home ({firstName, setFirstName, secondName, setSecondName, submitForm, setSubmitForm, ageMin, setAgeMin, ageMax, setAgeMax, selectTwo, setSelectTwo, selectOne, setSelectOne}) {
const FNNow = (e) => {
const first = e.target.value;
setFirstName(first)
}
const SNNow = (e) => {
const second = e.target.value;
setSecondName(second)
}
const SetAgeMin = (e) => {
const min = e.target.value;
setAgeMin(min);
}
const SetAgeMax = (e) => {
const max = e.target.value;
setAgeMax(max);
}
const FirstSelect = (e) => {
const fSel = e.target.value;
setSelectOne(fSel)
}
const SecondSelect = (e) => {
const sSel = e.target.value;
setSelectTwo(sSel)
}
const Submit = (e) => {
setSubmitForm([
...submitForm,
{FirstName: firstName, SecondName: secondName, MinAge: ageMin, MaxAge: ageMax, amA: selectOne, sA: selectTwo}])
}
return (
<div class="formDiv">
<div id='mainForm'>
<div class="row m-3">
<div class="col">
<input class="form-control form-control-lg" value={firstName} type="text" placeholder="First Name" onChange={FNNow} required/>
</div>
<div class="col">
<input class="form-control form-control-lg" value={secondName} type="text" placeholder="Second Name" onChange={SNNow} required/>
</div>
</div>
<div class="lineOne p-3">
<div class="iam"><h5>I am a:</h5>
<div class="px-4">
<select onChange={FirstSelect}>
<option type="text" >Man</option>
<option type="text" >Woman</option>
</select>
</div>
</div>
<div class="iam"><h5>Seeking a:</h5>
<div class="px-4">
<select onChange={SecondSelect}>
<option type="text" >Man</option>
<option type="text" >Woman</option>
</select>
</div>
</div>
</div>
<div class="lineOne p-3">
<div class="iam"><h5>Between ages:</h5>
<div class="px-4">
<input type="number" min="18" max="80" value={ageMin} onChange={SetAgeMin}/>
</div>
</div>
<div class="iam"><h5>and:</h5>
<div class="px-4">
<input type="number" min="18" max="80" value={ageMax} onChange={SetAgeMax}/>
</div>
</div>
</div>
<div class="btny p-3">
<button type="button" onClick={Submit} class="btn btn-primary btn-lg w-100 ms-3 me-3"><Link id="buttonLink" to="/profile">Submit</Link></button>
</div>
</div>
</div>
)
}
export default Home;
I have an input field in my react project to display a separate component when it's in a hover state. I have a separate component called [Focus Style] from the Actual component but all I'm doing is not working. The focus state should work with the first input field Kindly assist me. My code below.
Main Componenet
import React, { useState, useEffect } from "react";
import stays from "./Components/stays.json";
// import styled, {css} from "styled-components";
import FocusStyle from "../src/Components/FocusStyle";
export default function SearchGuest() {
const [guest, setGuest] = useState("");
const [location, setLocation] = useState("");
const [Data, setData] = useState([]);
const [filteredData, setFilteredData] = useState(Data);
const [focus, setFocus] = useState("false");
const onFocusChange = () => {
setFocus("true");
console.log("focused");
};
useEffect(() => {
setData(stays);
setFilteredData(stays);
}, []);
const handleSearch = (event) => {
event.preventDefault();
};
return (
<div>
<form action="" >
<input
onFocus={onFocusChange}
type="text"
name="guest"
id=""
// value={guest}
placeholder="text"
onChange={handleSearch}
style={focus ? { border: "1px solid yellow" } : <FocusStyle/> }
/>
<input
type="number"
name="location"
id=""
// value={location}
placeholder="number"
onChange={handleSearch}
/>
<button value="submit" >Search</button>
</form>
{console.log(filteredData)}
</div>
);
}
FocusStyle Component
import React from 'react'
export default function FocusStyle() {
return (
<div>
<h2 style={{marginTop: "90px", color: 'pink'}}>Focus Componenet</h2>
<div className="modal">
<div className="adult">
<span>Adult</span>
<button>-</button><span>0</span><button>+</button>
</div>
<div className="children">
<span>Children</span>
<button>-</button><span>0</span><button>+</button>
</div>
</div>
</div>
)
}
if so then you can do this
{focus ? <input
onFocus={onFocusChange}
type="text"
name="guest"
id=""
// value={guest}
placeholder="text"
onChange={handleSearch}
style={{ border: "1px solid yellow" }}
/>:
<FocusStyle/>
}
I'm trying to run this in react but it showing me error:
path.split is not a function
import React from 'react'
import './SendMail.css'
import CloseIcon from '#material-ui/icons/Close'
import { Button } from '#material-ui/core'
import { useForm } from 'react-hook-form'
function SendMail() {
const { register, handleSubmit, watch, errors } = useForm();
const onSubmit = (data) => {
console.log(data)
}
return (
<div className="sendMail">
<div className="sendMail_header">
<h3>New Message</h3>
<CloseIcon className="sendMail_close"/>
</div>
<form onSubmit={handleSubmit(onSubmit)}>
<input
name='to'
placeholder="To"
type="text"
ref = {register({required:true})}
/>
<input
name='subject'
placeholder="Subject"
type="text"
/>
<input
name='message'
placeholder="Message.."
type="text"
className="sendMail_message"
/>
<div className="sendMail_options">
<Button className="sendMail_send"
variant="contained"
color="primary"
type="submit"
>
Send
</Button>
</div>
</form>
</div>
)
}
Export default SendMail