How to correctly handle a select dropdown - javascript

I would to display multiple items in a select dropdown.
This is the code. But what i get back are many selects, one for each item i wanted to display in the dropdown.
mostraReferti(id) {
axios.get('http://localhost:8080/api/REFERTOs/' + id)
.then(response => {
this.setState({ referti: response.data }, () => {
console.log("response.data")
console.log("THIS.STATE", this.state);
})
})
.catch(err => console.log(err))
}
render() {
const refertiItems = this.state.referti.map((referti, i) => {
return (
<RefertiItems key={referti.hash_referto} item={referti} />
)
})
<Form>
<Label for="type" text="Referto" />
<div className="custom-select">
{refertiItems}
</div>
</Form>
And RefertiItems is :
render(){
console.log("SONO DENTRO")
return (
<div className={styles}>
<div className= "custom-select">
<Label for="type" text="Codice Referto" />
<select
name="codiceReferto"
placeholder="Selezionare Referto"
onKeyPress={this.onEnter} //allows you to move to the next panel with the enter key
value={this.codiceReferto}
onChange={this.handleInputChange}>
<option default value="vuoto"></option>
<option>{this.state.item.tipo_esame}-
{this.state.item.data_esame}</option>
</select>
</div>
</div>
What am i doing wrong?

First of all you have an issue with formatting. It is really difficult to understand something from code with wrong indents.
To fix your main issue you don't need to repeat your select component, just repeat options and pass it inside your select component, for example:
render() {
return (
<Form>
<Label for="type" text="Referto" />
<div className="custom-select">
<RefertiItems items={refertiItems} />
</div>
</Form>
);
}
RefertiItems:
render() {
const refertiItems = this.props.items.map((referti, i) => {
return (
<option key={referti.hash_referto}>
{referti.tipo_esame}-{referti.data_esame}
</option>
)
});
return (
<div className={styles}>
<div className= "custom-select">
<Label for="type" text="Codice Referto" />
<select
name="codiceReferto"
placeholder="Selezionare Referto"
onKeyPress={this.onEnter}
value={this.codiceReferto}
onChange={this.handleInputChange}
>
<option default value="vuoto"></option>
{refertiItems}
</select>
</div>
</div>
)
}

Related

How to receive all data (array) from dynamic input in react.js?

I am trying to receive data from a dynamic input (article), but it returns only an array with the two first element, I do not understand why, because I receive data from another dynamic input (chapitre) with no problems?
{
chapitreList.map(
(partItem, index) => {
return (
<div key={index}>
<label for="namec"> chapitre {index+1} :</label>
<input type="text" name='namec' id='namec' className ="form-control" value={partItem.chapitreName} />
<input type="number"
name='soldc'
id='soldc'
className ="form-control"
placeholder={partItem.chapitreDepense}
onChange={(e) =>
setchapitresolde((prev) => {
prev[index] = e.target.value;
return [...prev];
}
)
}
/>
<br />
{
partItem.articleList.map(
(artItem, inde) => {
return (
<div key={inde}>
<label for="namec"> article {inde+1} :</label>
<input type="text" name='namea' id='namea' className ="form-control" value={artItem.articleName} />
<input type="number"
name='solda'
id='solda'
class="form-control input-group-lg reg_name"
placeholder={artItem.articleDepense}
onChange={(e) =>
setarticlesolde((pre) => {
pre[inde] = e.target.value;
return [...pre];
})
}
/>
</div>
)
}
)
}
</div>
)
}
)
}

ReactJs | Show only the selected value in URL

I am new to reatJS. Can some genius please help me with my issue?
I am developing a e-pharmacy website where I let the users to first select a preferred districts and select a pharmacy from that area. I list out all the districts along with a drop down menu which shows all the pharmacies in that district. Then the user can make orders to the selected pharmacy.
I pass the selected pharmacy Id through the URL when user post an order.
If I had 3 districts, and I have selected a pharmacy from the third district, the URL appears like this:
http://localhost:3000/uploadlist?phmcy=&phmcy=&phmcy=1 (here the id of the selected pharmacy is "1")
The URL shows all the unselected values also. My preference is to display only the selected pharmacy's Id.
I want only the selected value to be displayed. Like this:
http://localhost:3000/uploadlist?phmcy=1
Here is my codes:
The district component: (Where the customer can select a district)
import React,{ Component } from 'react';
//import { Router } from 'react-router-dom/cjs/react-router-dom.min';
import { Link, withRouter } from "react-router-dom";
import './district.css';
import Upload from "./upload.component";
import Districtpharmacy from "./districtpharmacy.component";
class District extends React.Component{
state = {
pharmacy: []
};
render(){
return(
<div className="container">
<div className="container district">
<form action="/uploadlist" method="get">
<div className="row">
<div className="container header">
<h1>Select your District and Nearby Pharmacy</h1>
<p>Please select only one pharmacy</p>
</div>
</div>
<div className="row">
<div className="form-column">
<Districtpharmacy district="Mathara"/>
<Districtpharmacy district="Galle"/>
<Districtpharmacy district="Hambantota"/>
<Districtpharmacy district="Kalutara"/>
<Districtpharmacy district="Colombo"/>
<Districtpharmacy district="Gampaha"/>
<Districtpharmacy district="Rathnapura"/>
<Districtpharmacy district="Kurunegala"/>
</div>
<div className="form-column">
<Districtpharmacy district="Monaragala"/>
<Districtpharmacy district="Anuradhapura"/>
<Districtpharmacy district="Polonnaruwa"/>
<Districtpharmacy district="Kandy"/>
<Districtpharmacy district="Nuwara Eliya"/>
<Districtpharmacy district="Kegalla"/>
<Districtpharmacy district="Matale"/>
<Districtpharmacy district="Badulla"/>
<Districtpharmacy district="Ampara"/>
</div>
<div className="form-column">
<Districtpharmacy district="Puttalam"/>
<Districtpharmacy district="Trincomalee"/>
<Districtpharmacy district="Batticaloa"/>
<Districtpharmacy district="Mannar"/>
<Districtpharmacy district="Vavuniya"/>
<Districtpharmacy district="Mulaitivu"/>
<Districtpharmacy district="Kilinochchi"/>
<Districtpharmacy district="Jaffna"/>
</div>
</div>
<br/>
<button type="submit" >Add</button>
</form>
</div>
</div>
);
}
}
export default withRouter(District);
district.pharmacy component: (where the dropdown menu is returned.)
import React,{ Component } from 'react';
//import { Router } from 'react-router-dom/cjs/react-router-dom.min';
import { Link } from "react-router-dom";
import './district.css';
//import Upload from "./upload.component";
class Districtpharmacy extends React.Component{
state = {
pharmacy: [],
District: this.props.district
};
componentDidMount() {
console.log(this.state)
fetch("https://localhost:44357/api/Pharmacies?field=district&value="+this.props.district)
.then(response => response.json())
.then(pharmacy => this.setState({pharmacy: pharmacy}));
//console.log(this.state)
}
render(){
//console.log(this.state)
const pharm=this.state.pharmacy.map((pharmacies) =>{
return(<option value ={pharmacies.id}>{pharmacies.pharmacyname},{pharmacies.address}</option>)})
return(
<div>
<label class="label" for="district"><span>{this.props.district}</span></label>
<select name="phmcy" className="form-control select-dropdown"><option value="">Select Pharmacy</option>{pharm}</select>
</div>
)
}
}
export default Districtpharmacy
Can someone help me with this?
Edited:
The order posting form:
The parent file: (uploadlist.js)(the "phmcy" value is to be fetched from the url. this file is triggered after selecting the pharmacy)
export default function Uploadlist() {
let myphmcy = (new URLSearchParams(window.location.search)).get("phmcy")
console.log(myphmcy);
const ordersAPI= (url='https://localhost:44357/api/Orders') => {
return {
fetchAll: () => axios.get(url),
create: newRecord => axios.post(url, newRecord),
update: (id, updateRecord) => axios.put(url + id, updateRecord),
delete: id => axios.delete(url+id)
}
}
const addOrEdit = (formData, onSuccess) => {
ordersAPI().create(formData)
.then(res => {
onSuccess();
})
.catch(err => console.log(err.response.data))
}
return (
<div className="row">
<div className="jumbotron jumbotron-fluid py-4 "></div>
<div className="container text">
<h1 className="display-4"> Order Register</h1>
</div>
<div className="col-md-4 offset-3">
<Upload //this is the child component where the order form is built.
addOrEdit = {addOrEdit}
myphmcy = {myphmcy}
/>
</div>
<div className="col-md-1">
<div> </div>
</div>
</div>
)
}
the child file:
const initialFieldValues ={
orderID:0,
date_time:'',
status:'',
status2:'',
pharmacyName:'',
customerName:'',
patientName:'',
patientAge:'',
address:'',
email:'',
teleNo:'',
customer_id:1,
pharmacy_id:0,//data obtaind from the URL have to posted as the pharmacyID when posting.
image:'',
imageSource:'',
imageData: null
}
export default function Upload(props) {
const {addOrEdit} = props
const {myphmcy} = props
console.log(myphmcy);
const [values, setValues] = useState(initialFieldValues)
const[errors, setErrors] = useState({})
const handleInputChange= e => {
const {name, value} = e.target;
setValues({
...values,
[name]:value
})
}
/*const addOrEdit = (formData, onSuccess) => {
ordersAPI().create(formData)
.then(res => {
onSuccess();
})
.catch(err => console.log(err.response.data))
}*/
const showPreview = e => {
if(e.target.files && e.target.files[0]){
let imageData = e.target.files[0];
const reader = new FileReader();
reader.onload = x => {
setValues({
...values,
imageData,
imageSource : x.target.result
})
}
reader.readAsDataURL(imageData)
}
else{
setValues({
...values,
imageData:null,
imageSource:''
})
}
}
const validate = () => {
let temp = {}
temp.customerName = values.customerName == "" ? false : true;
setErrors(temp)
return Object.values(temp).every(x => x == true)
}
const resetForm = () => {
setValues(initialFieldValues)
document.getElementById('image-uploader').value = null;
}
const handleFormSubmit = e => {
e.preventDefault()
if (validate()){
const formData = new FormData()
formData.append('orderID',values.orderID)
formData.append('date_time',values.date_time)
formData.append('status',values.status)
formData.append('status2',values.status2)
formData.append('pharmacyName',values.pharmacyName)
formData.append('customerName',values.customerName)
formData.append('patientName',values.patientName)
formData.append('patientAge',values.patientAge)
formData.append('address',values.address)
formData.append('email',values.email)
formData.append('teleNo',values.teleNo)
formData.append('customer_id',values.customer_id)
formData.append('pharmacy_id',myphmcy)
formData.append('image',values.image)
formData.append('imageData',values.ImageData)
addOrEdit(formData, resetForm)
alert("Your file is being uploaded!")
}
}
const applyErrorClass = field => ((field in errors && errors[field] == false) ? ' invalid-field' : '')
return (
<>
<div className="container text-center ">
<p className="lead"></p>
</div>
<form autoComplete="off" noValidate onSubmit={handleFormSubmit}>
<div className="card">
<div className="card-header text-center">Place Your Order Here</div>
<img src={values.imageSource} className="card-img-top"/>
<div className="card-body">
<div className="form-group">
<input type="file" accept="image/*" className="form-control-file" onChange={showPreview} id="image-uploader"/>
</div>
<div className="form-group">
<input type="datetime-local" className="form-control" placeholder="Date Time" name="date_time" value={values.date_time}
onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Enter the prescription items and qty" name="status" value={values.status} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="What are the symptoms?" name="status2" value={values.status2} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Pharmacy Name" name="pharmacyName" value={values.pharmacyName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className={"form-control" + applyErrorClass('customerName')} placeholder="Your Name" name="customerName" value={values.customerName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Patient Name" name="patientName" value={values.patientName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Patient Age" name="patientAge" value={values.patientAge} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Delivery address" name="address" value={values.address} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Your Email" name="email" value={values.email} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Contact Number" name="teleNo" value={values.teleNo} onChange={ handleInputChange}/>
</div>
<div className="form-group text-center">
<button type="submit" className="btn btn-light">submit</button>
</div>
</div>
</div>
</form>
</>
)
}
The codes are so long. but I have uploaded them all for a better understanding of my issue.

I don't know where it went wrong in react js

I have created a 3 select option inputs based on 1st selection option it should populate the 2nd dropdown and based on 1st and 2nd selected option then it should populate the 3rd dropdown.
Unexpected token
const availableState = data.countries.find((c) => c.name === selectedCountry);
const availableCities = availableState?.states?.find((s) => s.name === selectedState);
render method select options
<div>
<label>Country</label>
<select
placeholder="Country"
value={selectedCountry}
onChange={(e) => setSelectedCountry(e.target.value)}
>
<option>--Choose Country--</option>
{data.countries.map((value, key) => {
return (
<option value={value.name} key={key}>
{value.name}
</option>
);
})}
</select>
</div>
<div>
<label>State</label>
<select
placeholder="State"
value={selectedState}
onChange={(e) => setSelectedState(e.target.value)}
>
<option>--Choose State--</option>
{availableState?.states.map((e, key) => {
return (
<option value={e.name} key={key}>
{e.name}
</option>
);
})}
</select>
</div>
<div>
<label>City</label>
<select
placeholder="City"
value={selectedCity}
onChange={(e) => setSelectedCity(e.target.value)}
>
<option>--Choose City--</option>
{availableCities?.cities.map((e, key) => {
return (
<option value={e.name} key={key}>
{e}
</option>
);
})}
</select>
</div>

Reactjs problems with radio buttons when fetch data

I want to build menu for my website with food cards. I fetch data(name of food, recipe, price) from my rest api and then i show this data on my react app. In this food card I have three radio buttons for mini, middle and maxi prices. When I change button on one card it changes on all cards. First image, when price 35 and
Second image, when I change price on first card, but it changes on all cards
this is my code:
constructor(props){
super(props);
this.state = {
shavermas : [],
price : ''
};
}
componentDidMount(){
this.findAllPosts();
}
findAllPosts(){
axios.get("http://localhost:8080/api/shaverma/all")
.then(response => response.data)
.then((data) => {
this.setState({shavermas: data})
});
}
onChange = e =>{
this.setState({price : e.target.value})
}
render(){
let {price} = this.state;
const {shavermas} = this.state;
return(
<>
{shavermas.map((shaverma, index) => (
<div className="food-cart">
<div className="product-img-div">
<img
src={shavermaPhoto}
className="d-inline-block product-img"
alt="shaverma"
/>
</div>
<div className="food-cart-body">
<div>
<h3>Шаверма <span>{shaverma.foodName}</span></h3>
<p>{shaverma.recipe}</p>
<form className="radio-buttons">
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMini} onChange={this.onChange} checked={price.charAt(0) == '' ? shaverma.priceMini : price == shaverma.priceMini}/>
<span>Mini</span>
</label>
</div>
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMiddle} onChange={this.onChange} checked={price == shaverma.priceMiddle}/>
<span>Middle</span>
</label>
</div>
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMaxi} onChange={this.onChange} checked={price == shaverma.priceMaxi} />
<span>Maxi</span>
</label>
</div>
</form>
<div className="food-cart-footer">
<strong>{price.charAt(0) === '' ? shaverma.priceMini : price}₴</strong>
<p>Хочу!</p>
</div>
</div>
</div>
</div>
))}
</>
)
}
You are using common Price state for all cards, you have to use price property for individual card,
Use it like this :
onChange = (e,index) =>{
let newShavermas = this.state.shavermas ;
newShavermas[index].price=e.target.value;
this.setState({price : e.target.value})
}
and while fetching the result include price property in each record
findAllPosts(){
axios.get("http://localhost:8080/api/shaverma/all")
.then(response => response.data)
.then((data) => {
let dataVal = data.map(ele=>ele.Price='');
this.setState({shavermas: dataVal })
});
}
and in return call onChange like this :
return(
<>
{shavermas.map((shaverma, index) => (
<div className="food-cart">
<div className="product-img-div">
<img
src={shavermaPhoto}
className="d-inline-block product-img"
alt="shaverma"
/>
</div>
<div className="food-cart-body">
<div>
<h3>Шаверма <span>{shaverma.foodName}</span></h3>
<p>{shaverma.recipe}</p>
<form className="radio-buttons">
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMini} onChange={(e)=>this.onChange(e,index)} checked={shaverma.price.charAt(0) == '' ? shaverma.priceMini : price == shaverma.priceMini}/>
<span>Mini</span>
</label>
</div>
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMiddle} onChange={(e)=>this.onChange(e,index)} checked={shaverma.price == shaverma.priceMiddle}/>
<span>Middle</span>
</label>
</div>
<div className="radio">
<label className="btn-radio">
<input type="radio" value={shaverma.priceMaxi} onChange={(e)=>this.onChange(e,index)} checked={shaverma.price == shaverma.priceMaxi} />
<span>Maxi</span>
</label>
</div>
</form>
<div className="food-cart-footer">
<strong>{shaverma.price.charAt(0) === '' ? shaverma.priceMini : shaverma.price}₴</strong>
<p>Хочу!</p>
</div>
</div>
</div>
</div>
))}
</>
)
This is because all of you cart items are looking at the same state value!
onChange = e =>{
this.setState({price : e.target.value}) < --- changes price to all cards
}
To solve this, you will need to have a price inside each shaverma then change it alone.
I would suggest starting by creating a FootCart component with its own state.
Something along the line of:
class FootCart implements React.Component {
...
render() {
return (
<div className="food-cart">
...
</div>
}
}
class Cards implements React.Component {
...
render(){
return (
<>
{shavermas.map((shaverma, index) => (<FootCart props/>)}
</>
}
}
Good Luck!

how to append drop down options inside render function?

below is my code. console.log of this.Resources result is shown below
1:"Basavaraj"
2:"Ashuthosh"
3:"Sravan"
4:"Raghavendra"
5:"Prem kumar"
6:"Simran"
7:"Namratha"
8:"Ghanashri"
9:"Ravindra"
10:"Anand"
11:"Shaeen"
render() {
console.log(this.Resources);
const options = this.Resources.map((item, index) =>{
<option key={index} value={item}>{item}</option>
});
return (
<div>
<form>
<div id="select">
<div className="container select">
<div className="row">
<select className="col-4 selectpicker input-large">
<option value="" disabled selected>Select resouce</option>
{options}
</select>
I want all data in this.Resources should come in select drop down options.
Thanks in advance
You are not returning the html in map.Need to return it.
const options = this
.Resources
.map((item, index) => {
return (
<option key={index} value={item}>{item}</option>
);
});
OR
ECMA6 arrow notation with default return:
const options = this
.Resources
.map((item, index) => (
<option key={index} value={item}>{item}</option>
));

Categories

Resources