I am stuck with a problem , I don't know how to do it. I want to display selected gifs , when I search its work properly , when I click on any gifs only this gifs is selected and display when I click on post button..
In This problem if anyone have any query please free feel to ask
App.js
This is the App.js file only single file I wrote my all code.
import "./App.css";
import { useEffect, useState } from "react";
import Axios from 'axios';
function App() {
const Api_key="QlYtlejKAxArXXXXXXXXXXXXXXXXX";
const Base_Url = "http://api.giphy.com/v1/gifs/search";
const [searchText,setSearchText] = useState("");
const [searchGif,setSearchGif] = useState("");
const [addText,setAddText] = useState([]);
const [gifs,setGifs] = useState([]);
const postValue = ()=>{
const addData = {
id:Date.now(),
name:searchText
}
console.log(addData);
setAddText([...addText,addData])
setSearchText("");
// Add Gifs
gifResponse();
}
const gifResponse = async()=>{
const response = await Axios.get(`${Base_Url}?api_key=${Api_key}&q=${searchGif}`)
// const res = await response.json();
setGifs(response.data.data);
console.log(response.data.data)
}
return (
<div className="App">
<div className="container">
<textarea
type="text"
className="form-control shadow-none mt-3"
rows="15"
cols="50"
placeholder="Write Something Here..."
value={searchText}
onChange={(e)=>setSearchText(e.target.value)}
/>
<div class="input-group mb-3 mt-2">
<input
type="text"
class="form-control shadow-none"
placeholder="Search Gif..."
aria-label="Recipient's username"
aria-describedby="basic-addon2"
value={searchGif}
onChange={(e)=>setSearchGif(e.target.value)}
/>
<div class="input-group-append">
<span class="input-group-text" id="basic-addon2" onClick={postValue}>
POST
</span>
</div>
</div>
{
addText.map((add,index)=>{
return <h4 key={index}>{add.name}</h4>
})
}
{
gifs.map((gif)=>{
return <img src={gif.images.fixed_height.url} />
})
}
</div>
</div>
);
}
export default App;
Related
staffForm.js
import React from 'react'
import { Link } from 'react-router-dom';
const StaffForm = ({handleSubmit},props) => {
// console.log(props);
const title = props.title;
const link =props.link;
return (
<section>
<div class="Employewrapper">
<div class="title">
{title} registration
</div>
<form class="form" onSubmit={handleSubmit} encType='multipart/form-data'>
<div class="inputfield">
<label>First Name</label>
<input required type="text" class="input" name='first_name'/>
</div>
<div class="inputfield">
<label>Last Name</label>
<input required type="text" class="input" name='last_name'/>
</div>
<div class="inputfield">
<label>Email</label>
<input required type="email" class="input" name='email'/>
</div>
<div class="inputfield">
<label>Password</label>
<input required type="password" class="input" name='password'/>
</div>
<div class="inputfield">
<label>Confirm password</label>
<input required type="password" class="input" name='confirm_password'/>
</div>
<div class="inputfield">
<label>Phone</label>
<input required type="tel" class="input" name='phone'/>
</div>
<div class="inputfield">
<label for="file">Profile Picture</label>
<input required type="file" id="file" accept="image/*" class="input" name='profile_picture'/>
</div>
<div class="inputfield">
<label>Birthdate</label>
<input required type="date" class="input" name='birthdate'/>
</div>
<div class="inputfield">
<label for="file">Id Card</label>
<input required type="file" id="file" accept="image/*" class="input" name='identification_card'/>
</div>
<div class="inputfield">
<input required type="submit" class="btn" />
</div>
<Link to={link} className='btn'>Back {title}</Link>
</form>
</div>
</section>
)
}
export default StaffForm;
DeliveryForm.js
import React from 'react'
import { Link } from 'react-router-dom';
import axios from 'axios';
import StaffForm from '../../Components/StaffForm';
import "../../Assets/styles/button.css"
const DeliveryForm = () => {
const url = 'http://127.0.0.1:8000/staff/delivery/';
const handleSubmit = (event)=>{
event.preventDefault();
const data = {
"user": {
"first_name": event.target.first_name.value,
"last_name": event.target.last_name.value,
"email": event.target.email.value,
"password": event.target.password.value,
"confirm_password": event.target.confirm_password.value,
"phone": event.target.phone.value
},
"profile_picture": event.target.profile_picture.files[0],
"birthdate": event.target.birthdate.value,
"identification_card": event.target.identification_card.files[0]
}
axios.request({
method: 'post',
headers: {
"Content-Type": "multipart/form-data",
},
url,
data
}).then(res => {
console.log(res)
})
}
return (
<>
<StaffForm handleSubmit={handleSubmit} title="Delivery" link="/Delivery"/>
</>
)
}
export default DeliveryForm
i have a particular form which i will be using for 3 api's the only difference are the title an the link i know the conventional way of writing props but it seems it not working in this case. on my page its not rendering anything but when i remove the props it works. i tried swithing the position of the props and the {handleSubmit}, when doing that i can see the prop but i can't post.
Just do it as you did with previous things in props.
const StaffForm = (props) => {
const handleSubmit = props.handleSubmit;
const title = props.title;
const link = props.link;
Or you will need to deconstruct everything in one place.
const StaffForm = ({ handleSubmit, title, link }) => {
Why: because props object is the first parameter, always. In my example you deconstruct it, and in your code - you deconstruct only handleSubmit from it and somewhy you were expecting to get a second parameter which you named props. No, only one and only first parameter is your props object.
Additionaly, you can use
const StaffForm = (props) => {
const { handleSubmit, title, link } = props;
or
// Spread operator
const StaffForm = ({handleSubmit, ...props}) => {
const { title, link } = props;
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;
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.
I am having issues with the axios post request. When I click on the Button, nothing happens. What is supposed to happen is that the data that I enter into the input fields is submitted to the API. However, no redirect or anything happens when I click the Button. I am not sure whether the onClick function in the Button is never being triggered or whether the issue lies with the call of axios and then the useNavigate function. I have tried several different ways of using these function but none worked. It might be a syntactic issue as I am a beginner with react. Any help would be appreciated!
Full Code:
import axios from 'axios';
import React, { useState } from 'react';
import { Container, Button } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
const AddContact = () => {
const [first_name, setFirstName] = useState("")
const [last_name, setLastName] = useState("")
const [mobile_number, setMobileNumber] = useState("")
const [home_number, setHomeNumber] = useState("")
const [work_number, setWorkNumber] = useState("")
const [email_address, setEmailAddress] = useState("")
const history = useNavigate();
const AddContactInfo = async () => {
let formField = new FormData();
formField.append('first_name', first_name)
formField.append('last_name', last_name)
formField.append('mobile_number', mobile_number)
formField.append('home_number', home_number)
formField.append('work_number', work_number)
formField.append('email_address', email_address)
await axios.post('http://localhost:8000/api/', {
data: formField
}).then(function (response) {
console.log(response.data);
history('/', { replace: true });
})
}
return (
<div>
<h1>Add contact</h1>
<Container>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your First Name"
first_name="first_name"
value={first_name}
onChange={(e) => setFirstName(e.target.value)} />
</div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Last Name"
last_name="last_name"
value={last_name}
onChange={(e) => setLastName(e.target.value)} />
</div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Mobile Number"
mobile_number="mobile_number"
value={mobile_number}
onChange={(e) => setMobileNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Home Number"
home_number="home_number"
value={home_number}
onChange={(e) => setHomeNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Work Number"
work_number="work_number"
value={work_number}
onChange={(e) => setWorkNumber(e.target.value)} /></div>
<div className="form-group">
<input type="text"
className="form-control form-control-lg"
placeholder="Enter Your Email Address"
email_address="email_address"
value={email_address}
onChange={(e) => setEmailAddress(e.target.value)} /></div>
<Button onClick={() => { AddContactInfo(); }}>
Add Contact
</Button>
</Container>
</div >
);
};
export default AddContact;
First rename AddContactInfo to addContactInfo and then:
<Button onClick={addContactInfo}>
Add Contact
</Button>
You should correct the method addContactInfo as below:
const AddContactInfo = () => {
let formField = new FormData();
formField.append('first_name', first_name)
formField.append('last_name', last_name)
formField.append('mobile_number', mobile_number)
formField.append('home_number', home_number)
formField.append('work_number', work_number)
formField.append('email_address', email_address)
axios.post('http://localhost:8000/api/', {
data: formField
}).then(function (response) {
console.log(response.data);
history('/', { replace: true });
})
}
Try This:
<Button onClick={AddContactInfo}>
Add Contact
</Button>
import axios from 'axios';
const url = 'http://localhost:8000/api/';
axios.post(url , formField)
.then(response => {
console.log(response.data);
history('/', { replace: true });
})
.catch(({response}) => {
console.log(response);
});
Try calling the function this way :)
<Button onClick={AddContactInfo}>
Add Contact
</Button>
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/>
}