React-select cannot read property value of undefined - javascript

I'm trying to implement 'react-select' but I am getting a 'TypeError: Cannot read property 'value' of undefined'. I am using react and react hooks. Although the demo usage uses a class component I am using a function component in this case. What am I doing wrong and how can I fix this?
job_req_titles is an object array with titles label: and value:
https://github.com/JedWatson/react-select
import React, { useState } from 'react';
import Select from 'react-select';
export default function CandidateForm({ handleCreate, job_req_titles }) {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [facebook, setFacebook] = useState('');
const [github, setGithub] = useState('');
const [linkedin, setLinkedin] = useState('');
const [jobTitle, setJobTitle] = useState('');
const [company, setCompany] = useState('');
const [appJobReq, setAppJobReq] = useState('');
const prepareCandidateObj = () => {
// Prepare the candidate object
let candidate = {
name,
email,
phone,
facebook,
github,
linkedin,
jobTitle,
company,
appJobReq,
};
console.log(candidate);
// Pass in the postNewCandidate from the parent component
// to be called in this component
handleCreate(candidate);
// alert('Candidate Submitted!');
};
return (
<div className='container'>
<div className='row'>
<label className='name'>Name</label>
</div>
<div className='row'>
<input
className='name-input'
type='text'
placeholder='Carol Caroller'
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className='row'>
<label className='email'>Email</label>
</div>
<div className='row'>
<input
className='email-input'
placeholder='example#email.com'
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className='row'>
<label className='phone'>Phone</label>
</div>
<div className='row'>
<input
className='phone-input'
placeholder='(201) 534 2233'
value={phone}
onChange={(e) => setPhone(e.target.value)}
/>
</div>
<div className='row'>
<label className='facebook'>Facebook</label>
</div>
<div className='row'>
<input
className='facebook-input'
placeholder='https://www.facebook.com/DilaonRion/'
value={facebook}
onChange={(e) => setFacebook(e.target.value)}
></input>
</div>
<div className='row'>
<label className='linkedin'>Linkedin</label>
</div>
<div className='row'>
<input
className='linkedin-input'
placeholder='https://www.linkedin.com/DillonRion/'
value={linkedin}
onChange={(e) => setLinkedin(e.target.value)}
></input>
</div>
<div className='row'>
<label className='github'>Github</label>
</div>
<div className='row'>
<input
className='github-input'
placeholder='https://www.github.com/DilonRion/'
value={github}
onChange={(e) => setGithub(e.target.value)}
></input>
</div>
<div className='row'>
<label className='job-title'>Job Title</label>
</div>
<div className='row'>
<input
className='job-title-input'
type='text'
placeholder='Frontend Developer'
value={jobTitle}
onChange={(e) => setJobTitle(e.target.value)}
></input>
</div>
<div className='row'>
<label className='current-company'>Current Company Name</label>
</div>
<div className='row'>
<input
className='current-company-input'
type='text'
placeholder='Obrien LLC'
value={company}
onChange={(e) => setCompany(e.target.value)}
></input>
</div>
<div className='row'>
<label className='job-req'>Applicant Job Req</label>
</div>
<div className='row'>
<div className='job-req-input'>
<Select
className='job-req-select'
value={appJobReq}
onChange={(e) => setAppJobReq(e.target.value)}
options={job_req_titles}
isMulti
/>
</div>
</div>
{/* <div className='row'>
<label className='cv'>CV</label>
</div> */}
<div className='row'>
<label className='applied'>Applied or Sourced</label>
<select className='applied-input'>
<option disabled defaultValue>
--
</option>
<option value='1'>Applied</option>
<option value='0'>Sourced</option>
</select>
</div>
<button className='create-button' onClick={prepareCandidateObj}>
Create
</button>
</div>
);
}

adding this fixed the error.
const handleChange = (selectedOption) => {
setAppJobReq(selectedOption);
console.log(`Option selected:`, selectedOption);
};
<div className='job-req-input'>
<Select
className='job-req-select'
value={appJobReq}
onChange={handleChange}
options={job_req_titles}
isMulti
classNamePrefix='select'
/>
</div>

Related

How to add a background image avatar to React JS using primereact

I am trying to create a register page where a user can add a profile picture as well as a background picture to their profile. I have installed the PrimeReact themes and templates to my node modules. However, the avatar doesn't want to fit it to where it can make a background image avatar. Instead, it just fits it as a circle just like the profile picture avatar instead of a rectangle fit as a background image avatar.
import {useState, useEffect } from 'react'
import Avatar from 'react-avatar-edit'
import {Dialog} from 'primereact/dialog'
import {InputText} from 'primereact/inputtext'
const initialState = {
company: '',
email: '',
password: '',
isMember: true,
}
const Register = () => {
const [imagecrop, setimagecrop] = useState(false);
const [image, setImage] = useState("");
const [src, setsrc] = useState(false);
const [profile, setProfile] = useState([]);
const [pview, setpview] = useState(false);
const profileFinal = profile.map((item) => item.pview);
const onClose = () => {
setpview(null);
};
const onCrop = (view) => {
setpview(view);
};
const saveCropImage = () => {
setProfile([...profile, { pview }]);
setimagecrop(false);
}
const [values, setValues] = useState(initialState)
// global state and useNavigate
const handleChange = (e) => {
console.log(e.target)
}
const onSubmit = (e) => {
e.preventDefault()
console.log(e.target)
}
return (
<body class="page-template-default page page-id-13">
<header class="site-header">
<div class="container">
<h1 class="school-logo-text float-left"><strong>Direct</strong> Connection</h1>
<div class="site-header__util">
</div>
</div>
</header>
<div class="page-banner">
<div class="page-banner__bg-image" style={ { backgroundImage: "url('connection.jpg')" } }></div>
<div class="page-banner__content container container--narrow">
<h1 class="page-banner__title">Add Your Company</h1>
<div class="page-banner__intro">
<p></p>
</div>
</div>
</div>
<div class="container container--narrow page-section">
<h2 class="headline headline--tiny">Want to join and connect with companies? Sign up and get your company out there:</h2>
<label class="profile-pic">Profile Photo:</label>
<div class="profile-img">
<Dialog
visible={imagecrop}
header={() => (
<p htmlFor="" class="text 2xl font-semibold textColor">
</p>
)}
onHide={() => setimagecrop(false)}
></Dialog>
<div class="confirmation-content flex flex-column align-items-center">
<Avatar
width={500}
height={400}
onCrop={onCrop}
onClose={onClose}
src={src}
shadingColor={"#474649"}
backgroundColor={"#474649"}
></Avatar>
<div class="flex flex-column align-items-center mt-5 w-12">
<div class="flex justify-content-around w-12 mt-4">
</div>
</div>
<InputText
type="file"
accept='/image/*'
style={{ display: "none" }}
onChange={(event)=>{
const file = event.target.files[0];
if(file && file.type.substring(0,5)==="image"){
setImage(file);
}else{
setImage(null)
}
}}
/>
</div>
</div>
<script src="profile-pic.js"></script>
<label class="profile-back">Background Photo:</label>
<div>
<Dialog
visible={imagecrop}
header={() => (
<p htmlFor="" class="text 2xl font-semibold textColor">
</p>
)}
onHide={() => setimagecrop(false)}
></Dialog>
<Avatar
width={1000}
height={400}
onCrop={onCrop}
onClose={onClose}
src={src}
shadingColor={"#474649"}
backgroundColor={"#474649"}
></Avatar>
<InputText
type="file"
accept='/image/*'
style={{ display: "none" }}
onChange={(event)=>{
const file = event.target.files[0];
if(file && file.type.substring(0,5)==="image"){
setImage(file);
}else{
setImage(null)
}
}}
/>
<img class="background-image" src=""></img>
</div>
<div class="company-info-container page-section">
<label class="company-name">Company Name</label>
<div class="company-input">
<input text="headline headline--input" placeholder="Enter Company"></input>
</div>
<label class="company-email">Email</label>
<div class="email-input">
<input text="headline headline--input" placeholder="Enter Email"></input>
</div>
<label class="company-address">Company Address</label>
<div class="address-input">
<input text="headline headline--input" placeholder="Enter Address"></input>
</div>
<label class="company-city">City</label>
<div class="city-input">
<input text="headline headline--input" placeholder="Enter City"></input>
</div>
<label class="company-zip">Zip Code</label>
<div class="zip-input">
<input text="headline headline--input" placeholder="Enter Zip"></input>
</div>
<label class="company-password">Password</label>
<div class="password-input">
<input text="headline headline--input" placeholder="Enter Password"></input>
</div>
<label class="company-password">Retype Password</label>
<div class="reword-input">
<input text="headline headline--input" placeholder="Re Password"></input>
</div>
<label class="company-description">Tell us about your company and what you do!</label>
<div class="description-input">
<textarea rows="5" cols="80" id="TITLE" text="headline headline--input" placeholder="Description"></textarea>
</div>
</div>
<button type="button" class="btn btn--large btn--orange push-right">Add Your Company</button>
</div>
<footer class="site-footer">
<div class="site-footer__inner container container--narrow">
<div class="group">
<div class="site-footer__col-one">
<h1 class="school-logo-text school-logo-text--alt-color">
<strong>Direct</strong> Connection
</h1>
<p><a class="site-footer__link" href="index.html">706-263-0175</a></p>
</div>
</div>
</div>
</footer>
</body>
)
}
export default Register
I have tried looking at how primereact avatars can reshape the circle to rectangle to fit the image to a background image but I don't see many ways of how it can be reshaped.

How to render new page with react-router-dom in a function?

I am creating an application where I am getting a parameter from a function and if the parameter equals true I would render a new route instead.
I know how to use react-router-dom as to render new routes you would use something like this
<Link to="/login">Login</Link>
But I don't know how to call it in a function.
function functionName(success){
if (success){
//What do I write here?
// Something like go to path="/login"
}
}
Thank you
(edit)
import { useContext, useState, useEffect } from "react";
import { AuthContext } from "../../Context Api/authenticationAPI";
import { FaUserPlus } from "react-icons/fa";
import { Link, useHistory } from "react-router-dom";
import Alerts from "./Alerts";
const Register = () => {
const history = useHistory();
const { addUser } = useContext(AuthContext);
const data = useContext(AuthContext).data;
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
useEffect(() => {
console.log(data);
if (data.success) {
history.push("/login");
}
}, [data]);
return (
<div className="row mt-5">
<div className="col-md-6 m-auto">
<div className="card card-body">
<h1 className="text-center mb-3">
<i>
<FaUserPlus />
</i>{" "}
Register
</h1>
<Alerts />
<form>
<div className="mb-2">
<label>Name</label>
<input
type="name"
id="name"
name="name"
className="form-control"
placeholder="Enter Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="mb-2">
<label>Email</label>
<input
type="email"
id="email"
name="email"
className="form-control"
placeholder="Enter Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="mb-2">
<label>Password</label>
<input
type="password"
id="password"
name="password"
className="form-control"
placeholder="Create Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button
onClick={(e) => {
e.preventDefault();
addUser({ name, email, password });
}}
className="btn btn-primary col-12"
>
Register
</button>
<p className="lead mt-4">
Have An Account? <Link to="/login">Login</Link>
</p>
</form>
</div>
</div>
</div>
);
};
export default Register;
import React from "react";
import { Link } from "react-router-dom";
import { FaSignInAlt } from "react-icons/fa";
const Login = () => {
return (
<div className="row mt-5">
<div className="col-md-6 m-auto">
<div className="card card-body">
<h1 className="text-center mb-3">
<i>
<FaSignInAlt />
</i>{" "}
Login
</h1>
<div className="mb-2">
<label>Email</label>
<input
type="email"
id="email"
name="email"
className="form-control"
placeholder="Enter Email"
/>
</div>
<div className="mb-2">
<label>Password</label>
<input
type="password"
id="password"
name="password"
className="form-control"
placeholder="Enter Password"
/>
</div>
<button className="btn btn-primary col-12">Login</button>
<p className="lead mt-4">
No Account? <Link to="/register">Register</Link>
</p>
</div>
</div>
</div>
);
};
export default Login;
You can make use of the history object and programmatically navigate using history.push()
import { useHistory } from 'react-router-dom'
const history = useHistory();
function functionName(success){
if (success) {
history.push('/login')
}
}
Reference
useHistory Hook

React Hook Form: How to reset the form content after submission

I have a hidden field when you clicked the YES option, I want to reset the form to hide again the field after successful submission.
Below is my code and here is the link to sandbox.
import { React, useState } from "react";
import emailjs from "emailjs-com";
import { useForm } from "react-hook-form";
const NameForm = () => {
const [showYes, setShowYes] = useState(false);
const {
register,
handleSubmit,
reset,
formState: { errors }
} = useForm({
defaultValues: { yes_no: false, yes_i_understand: false }
});
const sendEmail = formData => {
emailjs
.send("YOUR_SERVICE_ID", "YOUR_TEMPLATE_ID", formData, "YOUR_USER_ID")
.then(
result => {
console.log(result.text);
},
error => {
console.log(error.text);
}
);
reset();
};
return (
<div>
<h1 className="text-center text-md-left mb-3">Get in Touch</h1>
<p>Have you spoken to a us in the last 14 days?</p>
<form className="contact-form" onSubmit={handleSubmit(sendEmail)}>
<div className="mb-2">
<div className="form-check form-check-inline">
<input
className="form-check-input"
type="radio"
value="Yes"
id="yes"
name="yes_no"
onClick={setShowYes}
/>
<label className="form-check-label mr-4" htmlFor="yes">
Yes
</label>
</div>
<div className="form-check form-check-inline">
<input
className="form-check-input"
type="radio"
value="No"
id="no"
name="yes_no"
defaultChecked
onClick={() => setShowYes(false)}
/>
<label className="form-check-label mr-4" htmlFor="no">
No
</label>
</div>
</div>
{showYes && (
<div className="form-group row mb-0">
<div className="col-12 py-3">
<input
type="text"
className="form-control custom--fields-mod text-the-primary"
id="agentName"
placeholder="Agent Name *"
name="agent_name"
{...register("agent_name", { required: true })}
/>
{errors.agent_name && (
<span className="invalid-feedback d-block">
Please fill out this field.
</span>
)}
</div>
</div>
)}
<div className="form-group mb-0 py-3">
<textarea
className="form-control custom--fields-mod text-the-primary"
id="message"
rows="3"
placeholder="Message *"
name="message"
{...register("message", { required: true })}
></textarea>
{errors.message && (
<span className="invalid-feedback d-block">
Please fill out this field.
</span>
)}
</div>
<div className="form-group row py-2 mb-0">
<div className="col-12 text-center text-md-left py-2 py-md-0">
<input
className="buttons-width float-md-right btn btn-dark-moderate-orange rounded-0"
type="submit"
value="SEND MESSAGE"
/>
</div>
</div>
</form>
</div>
);
};
export default NameForm;
I'm not sure if I missed something on passing the data to the form. I also put defaultChecked attribute in option NO.
The 'showYes' state should be reset to false after submission.
I updated some codes.
https://codesandbox.io/s/react-hook-form-using-emailjs-2-forked-fmido?file=/src/App.js
const resetForm = () => {
reset();
setShowYes(false);
};
const sendEmail = (formData) => {
emailjs
.send("YOUR_SERVICE_ID", "YOUR_TEMPLATE_ID", formData, "YOUR_USER_ID")
.then((result) => {
console.log(result.text);
resetForm();
},
(error) => {
console.log(error.text);
}
);
};
I'm not sure if I missed something on passing the data to the form. I also put defaultChecked attribute in option NO.
<input
className="form-check-input"
type="radio"
value="true"
id="yes"
name="yes_no"
{...register("yes_no", { required: true })}
onClick={setShowYes}
/>
<label className="form-check-label mr-4" htmlFor="yes">
Yes
</label>

How to create this 3 button in react Js?

I'm trying to create this 3 button but I can't create third button because I don't know how use multiple useState in React Js.
This is my code :
const ShowOrNot = () => {
const [showForm, setShowForm] = useState(false);
const [showPreview , setShowPreview] = useState(false)
return (
<div className="col-12">
{showForm ? (
<div className={"content-send-form-wrapper"} id="scrollbar-style">
<div className={"content-send-form-header"}>
<div className={"content-send-form-header-title"}>
</div>
<h2>
New Upload
</h2>
<div className={"content-send-form-close-btn"}>
<button onClick={() => setShowForm(false)} className={"close-modal-btn"}>
Close <span></span>
</button>
</div>
</div>
<form className={"mt-3 content-send-form-data register-teacher-inputs-box "}>
<Row>
<div className={"col-lg-6 col-12 mt-4"}>
<label
htmlFor={"name"} className={" text-right"}>
<span>*</span>
</label>
<input type="text" className="form-control" placeholder={"عنوان"}
name={""} required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => e.target.placeholder = "عنوان"}
onFocus={(e) => e.target.placeholder = ""}
/>
</div>
<div className={"col-lg-6 col-12 mt-4"}>
<label
htmlFor={"country"} className={" text-right"}>
<span>*</span>
</label>
<input type="text" className="form-control" placeholder={"دسته بندی"}
name={"country"}
// value={this.country}
// onChange={this.onChange}
required="true"
onBlur={(e) => e.target.placeholder = "دسته بندی"}
onFocus={(e) => e.target.placeholder = ""}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3">
<label
htmlFor={"name"} className={"label-full-size text-right"}>
<span>*</span>
</label>
<input type="text" className="form-control" placeholder={"خلاصه توضیحات"}
name={""} required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => e.target.placeholder = "خلاصه توضیحات"}
onFocus={(e) => e.target.placeholder = ""}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3">
<label
htmlFor={"name"} className={"label-full-size text-right textarea-label"}>
<span>*</span>
</label>
<textarea className="video-text-form form-control" placeholder={"متن ویدیو"}
name={""} required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => e.target.placeholder = "متن ویدیو"}
onFocus={(e) => e.target.placeholder = ""}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3 video-upload-input-btn">
<VideoUpload />
</div>
</Row>
<Row>
<div className="col-lg-6 col-12 mt-3">
<PosterUpload />
</div>
<div className="col-lg-6 col-12 mt-3">
<CoverUpload />
</div>
</Row>
</form>
{showPreview ? (
<div>
show preview
</div>
) : (<Row>
<div className="col-lg-8 col mt-3">
<button className="preview-send-data-btn" onClick={function(event){ setShowPreview(true); setShowForm(true)}}>
Preview
</button>
</div>
<div className="col-lg-4 col mt-3">
<button className="draft-send-data-btn">
Draft
</button>
</div>
</Row>)}
</div>
) : (
<div>
<button className="upload-content-btn w-100" onClick={() => setShowForm(true)}>
<span className="ml-2">
</span>New Upload </button>
</div>
)}
</div>
);
};
ReactDOM.render(<ShowOrNot />, document.getElementById("root"))
I want when click on Preview button showFrom not show and other form that in showPreview display instead. My problem is not about CSS and just I don't know how to use useState like before steps I used it.
In your example Preview inside of Form, so if you hide form preview will be hidden too.
You need to properly organize components so your code will be easy to read and understand. Without that you can not solve any complex enough task.
Can start like this.
const ShowOrNot = () => {
const [showForm, setShowForm] = useState(false);
const [showPreview, setShowPreview] = useState(false);
const [formHidden, setFormHidden] = useState(false);
return (
<div className="col-12">
{!showForm ? (
<ShowFormButton onClick={() => setShowForm(true)} />
) : undefined}
{showForm ? (
<div className={'content-send-form-wrapper'} id="scrollbar-style">
<div className={'content-send-form-header'}>
<div className={'content-send-form-header-title'}></div>
<h2>New Upload</h2>
<HideFormButton
onClick={() => {
setShowForm(false);
}}
/>
</div>
{!formHidden ? <MyForm /> : undefined}
{!showPreview ? (
<ShowPreviewButton
onClick={() => {
setShowPreview(true);
setFormHidden(true);
}}
/>
) : undefined}
{showPreview ? (
<div>
Preview
<SendButton
onClick={() => {
setFormHidden(false);
setShowPreview(false);
setShowForm(false);
}}
/>
</div>
) : undefined}
</div>
) : undefined}
</div>
);
};
function SendButton({ onClick }) {
return (
<div>
<button className=" w-100" onClick={onClick}>
<span className="ml-2"></span>Send
</button>
</div>
);
}
function ShowFormButton({ onClick }) {
return (
<div>
<button className="upload-content-btn w-100" onClick={onClick}>
<span className="ml-2"></span>New Upload{' '}
</button>
</div>
);
}
function ShowPreviewButton({ onClick }) {
return (
<Row>
<div className="col-lg-8 col mt-3">
<button className="preview-send-data-btn" onClick={onClick}>
Preview
</button>
</div>
<div className="col-lg-4 col mt-3">
<button className="draft-send-data-btn">Draft</button>
</div>
</Row>
);
}
function HideFormButton({ onClick }) {
return (
<div className={'content-send-form-close-btn'}>
<button onClick={onClick} className={'close-modal-btn'}>
<span>Close</span>
</button>
</div>
);
}
function MyForm() {
return (
<form
className={'mt-3 content-send-form-data register-teacher-inputs-box '}
>
<Row>
<div className={'col-lg-6 col-12 mt-4'}>
<label htmlFor={'name'} className={' text-right'}>
<span>*</span>
</label>
<input
type="text"
className="form-control"
placeholder={'عنوان'}
name={''}
required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => (e.target.placeholder = 'عنوان')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
<div className={'col-lg-6 col-12 mt-4'}>
<label htmlFor={'country'} className={' text-right'}>
<span>*</span>
</label>
<input
type="text"
className="form-control"
placeholder={'دسته بندی'}
name={'country'}
// value={this.country}
// onChange={this.onChange}
required="true"
onBlur={(e) => (e.target.placeholder = 'دسته بندی')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3">
<label htmlFor={'name'} className={'label-full-size text-right'}>
<span>*</span>
</label>
<input
type="text"
className="form-control"
placeholder={'خلاصه توضیحات'}
name={''}
required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => (e.target.placeholder = 'خلاصه توضیحات')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3">
<label
htmlFor={'name'}
className={'label-full-size text-right textarea-label'}
>
<span>*</span>
</label>
<textarea
className="video-text-form form-control"
placeholder={'متن ویدیو'}
name={''}
required="true"
// value={this.name}
// onChange={this.onChange}
onBlur={(e) => (e.target.placeholder = 'متن ویدیو')}
onFocus={(e) => (e.target.placeholder = '')}
/>
</div>
</Row>
<Row>
<div className="col-12 mt-3 video-upload-input-btn">
<VideoUpload />
</div>
</Row>
<Row>
<div className="col-lg-6 col-12 mt-3">
<PosterUpload />
</div>
<div className="col-lg-6 col-12 mt-3">
<CoverUpload />
</div>
</Row>
</form>
);
}
ReactDOM.render(<ShowOrNot />, document.getElementById('root'));
you should use setState like this code
setShowForm(false) or setShowForm(true)
and
setShowPreview(true) or setShowPreview(false)

How to merge/join two components Parent/Child state react

A newbie plight to how to handle/merge state. I have an inventory UI I'm trying to create, what I want to achieve is this, every time a new item gets added to ItemVariation, it appends to the Item component. I'm using a Django backend not that it matters but I want to add ItemVaration as a reverse relation to Item Table.
something like this.
state = [{Item},[{ItemVariation}, {ItemVariation}]]
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import ItemVariation from './ItemVariation';
export const Item = (props) => {
const fetchCategory = 'http://localhost:8000/api/product/categories/'
const fetchManufacturer = 'http://localhost:8000/api/product/manufacturers/'
const fetchBranch = 'http://localhost:8000/api/users/branch/'
const [manufacturer, setManufacturer] = useState([])
const [categories, setCategories] = useState([])
const [branch, setBranch] = useState([])
const [item, setItem] = useState({
name: '',
category: categories,
branch: branch,
manufacturer: manufacturer,
has_size: false,
})
useEffect(() => {
const cat = axios.get(fetchCategory);
const man = axios.get(fetchManufacturer);
const bra = axios.get(fetchBranch);
axios.all([cat, man, bra]).then(axios.spread((...responses) => {
setCategories(responses[0].data)
setManufacturer(responses[1].data)
setBranch(responses[2].data)
// use/access the results
})).catch(errors => {
// react on errors.
console.log(errors)
})
}, [])
return (
<div>
<div>
<label htmlFor="name">Name: </label>
<input type="text" id="name" name="name" />
</div>
<div>
<label htmlFor="category">Categories: </label>
<select name="category" id="category" >
{categories.map((category, index)=>(
<option key={index} value={category.id}>{category.name}</option>
))}
</select>
</div>
<div>
<label htmlFor="category">Manufacturer: </label>
<select name="category" id="category" >
{manufacturer.map((man, index)=>(
<option key={index} value={man.id}>{man.name}</option>
))}
</select>
</div>
<div>
<label htmlFor="category">Branch: </label>
<select name="branch" id="branch" >
{branch.map((bra, index)=>(
<option key={index} value={bra.id}>{bra.name}</option>
))}
</select>
</div>
<div>
<div>
<label htmlFor="has_size">Has Size: </label>
<input type="radio" id="has_size" name="has_size" />
</div>
</div>
<hr/>
{JSON.stringify(item, null, 2)}
<ItemVariation />
</div>
import React, { useState } from 'react'
function ItemVariation(props) {
const fields = {
default_product_variation: '',
color: '',
price: '',
quantity: '',
model_number: '',
sku: '',
barcode: '',
product_condition: '',
size: '',
extra_information: ''
}
const [variations, setVariations] = useState([fields])
const handleAddItem = () => {
setVariations([...variations, fields])
}
return (
<div>
{variations.map((variation, index) => (
<div key={index}>
<div>
<label htmlFor="default_product_variation">Make default: </label>
<input type="radio" id="default_product_variation" name="default_product_variation" />
</div>
<div>
<label htmlFor="color">Color: </label>
<input type="text" id="color" name="color" />
</div>
<div>
<label htmlFor="price">Price: </label>
<input type="number" id="price" name="price" />
</div>
<div>
<label htmlFor="wholesale_price">Wholesale Price: </label>
<input type="number" id="wholesale_price" name="wholesale_price" />
</div>
<div>
<label htmlFor="quantity">Quantity: </label>
<input type="number" id="quantity" name="quantity" />
</div>
<div>
<label htmlFor="model_number">Model Number: </label>
<input type="text" id="model_number" name="model_number" />
</div>
<div>
<label htmlFor="sku">SKU: </label>
<input type="text" id="sku" name="sku" />
</div>
<div>
<label htmlFor="barcode">Barcode: </label>
<input type="text" id="barcode" name="barcode" />
</div>
<div>
<div>
<label htmlFor="product_condition">Condition: </label>
<select name="product_condition" id="product_condition">
<option value="1">New</option>
<option value="2">Refurbished</option>
<option value="3">Repurposed</option>
</select>
</div>
</div>
<div>
<label htmlFor="size">Size: </label>
<input type="text" id="size" name="size" />
</div>
<div>
<label htmlFor="extra_information">Extra Information: </label>
<textarea id="extra_information" name="extra_information"></textarea>
</div>
<hr />
</div>
))}
<button type="button" onClick={handleAddItem}>Add Another Item</button>
{JSON.stringify(variations, null, 2)}
</div>
)
}
export default ItemVariation
How do I approach this?

Categories