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

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>
)
}
)
}

Related

REACT: SELECT from MYSQL

i a new user and a new in React world. I need help to solve this situation about a Select with values from mysql DB.
I receive the values, but the select goes in infinite loop.
The error is surely in this file cause server.js works without problem!!
Really thanks for the help, and sorry if it could be a stupid question. I m studying react from one week and i have not found answers on internet
function FormAddMenu({ registerMenu }) {
const [nomeMenuReg, setNomeMenuReg] = useState("");
const [descrizioneMenuReg, setDescrizioneMenuReg] = useState("");
const [prezzoMenuReg, setPrezzoMenuReg] = useState("");
const [disponibilitaMenuReg, setDisponibilitaMenuReg] = useState("");
const [portataMenuReg, setPortataMenuReg] = useState("");
const [addMenu, setAddMenu] = useState({
portataMenuReg: "",
nomeMenuReg: "",
descrizioneMenuReg: "",
prezzoMenuReg: "",
disponibilitaMenuReg: "",
});
const [portate, setPortate] = useState({ value: "", label: "" });
const selectOptions = async () => {
Axios.post("http://localhost:3001/selectPortata").then((response) => {
// console.log("risposta:",response.data)
setPortate(
response.data.map((risp) => ({
...setPortate,
value: risp.value,
label: risp.label,
})),
);
});
};
selectOptions();
console.log("portate:", portate);
const submitHandler = (e) => {
e.preventDefault();
registerMenu(addMenu);
document.getElementById("addmenu").reset();
};
const handleCheckbox = (e) => {
console.log(e.target.checked);
if (e.target.checked === true) {
setAddMenu({ ...addMenu, disponibilitaMenuReg: 1 });
} else {
setAddMenu({ ...addMenu, disponibilitaMenuReg: e.target.value });
}
};
return (
<div className="container width85">
<h1>CREA IL MENU'</h1>
<form id="addmenu">
<div className="mb-3">
<label htmlFor="portataMenuReg" className="form-label">
PORTATA
</label>
<Select
options={portate}
onChange={(e) => setAddMenu({ ...addMenu, portataMenuReg: e.target.value })}
className="mb-3"
/>
</div>
<div className="mb-3">
<label htmlFor="nomeMenuReg" className="form-label">
NOME
</label>
<input
type="text"
onChange={(e) => setAddMenu({ ...addMenu, nomeMenuReg: e.target.value })}
className="form-control"
id="nomeMenuReg"
rows="3"
/>
</div>
<div className="mb-3">
<label htmlFor="descrizioneMenuReg" className="form-label">
DESCRIZIONE
</label>
<textarea
className="form-control"
onChange={(e) =>
setAddMenu({ ...addMenu, descrizioneMenuReg: e.target.value })
}
id="descrizioneMenuReg"
rows="3"
></textarea>
</div>
<div className="mb-3">
<label htmlFor="prezzoMenuReg" className="form-label">
PREZZO
</label>
<input
type="text"
className="form-control"
onChange={(e) => setAddMenu({ ...addMenu, prezzoMenuReg: e.target.value })}
id="prezzoMenuReg"
rows="3"
/>
</div>
<div className="mb-3">
<label htmlFor="disponibilitaMenuReg" className="form-label">
DISPONIBILITA'
</label>
<input
type="checkbox"
value="0"
className="htmlForm-control"
onChange={handleCheckbox}
id="disponibilitaMenuReg"
rows="3"
/>
</div>
<div className="mb-3">
<button type="submit" onClick={submitHandler} className="btn btn btn-danger">
AGGIUNGI AL MENU
</button>
</div>
</form>
</div>
);
}
export default FormAddMenu;
Wrap the selectOptions(); call in an useEffect (since loading data and mutating state based on it is a side effect).
The empty dependency array (documented above) means the effect is only executed once on mount.
React.useEffect(() => {
selectOptions();
}, []);

Uncaught TypeError: Cannot read properties of undefined (reading 'roll')

I keep running into this error. I have tried defining the variables but it still does not seem to work. I may be doing this wrong or its something very small but i cant seem to figure it out. I would appreciate the help.
Uncaught ReferenceError: process is not defined
this is another error which im guessing is from the same issue.
This is my code below:
import React, { Component } from "react";
import { Button, Form, FormGroup, Label, Input, Col, Row } from "reactstrap";
import Loading from "./LoadingComponent";
class Issue extends Component {
constructor(props) {
super(props);
this.state = {
isbn: "",
roll: "",
};
}
componentDidMount() {
window.scrollTo(0, 0);
}
render() {
if (this.props.booksLoading || this.props.usersLoading) {
return (
<div className="container">
<div className="row">
<Loading />
</div>
</div>
);
} else if (this.props.booksErrMess) {
return (
<div className="container loading">
<div className="row heading">
<div className="col-12">
<br />
<br />
<br />
<br />
<h3>{this.props.booksErrMess}</h3>
</div>
</div>
</div>
);
} else if (this.props.usersErrMess) {
return (
<div className="container loading">
<div className="row heading">
<div className="col-12">
<br />
<br />
<br />
<br />
<h3>{this.props.usersErrMess}</h3>
</div>
</div>
</div>
);
}
else {
const bookoptions = this.props.books.map((book, index) => (
<option key={book.isbn}>{book.isbn}</option>
));
const defaultBook = this.props.books[0];
// To just get list of the students (not the admins)
let useroptions = this.props.users.filter((user) => !user.admin);
const defaultUser = useroptions[0];
useroptions = useroptions.map((user, index) => (
<option key={user.roll}>{user.roll}</option>
));
if (this.state.isbn === "") {
this.setState({ isbn: defaultBook.isbn, roll: defaultUser.roll });
}
return (
<div className="container full">
<div className="row justify-content-center heading">
<div className="col-12">
<h3 align="center"> Issue book</h3>
</div>
</div>
<div className="row row-content justify-content-center">
<Form
onSubmit={(e) => {
let bookid = this.props.books.filter(
(book) => book.isbn === this.state.isbn
)[0]._id;
let studentid = this.props.users.filter(
(user) => user.roll === this.state.roll
)[0]._id;
this.props.postIssue(bookid, studentid);
e.preventDefault();
}}
>
<FormGroup row>
<Label htmlFor="isbn"> ISBN No.of book</Label>
<Input
type="select"
defaultValue={defaultBook.name}
name="isbn"
id="isbn"
className="form-control"
onInput={(e) => {
this.setState({ isbn: e.target.value });
}}
>
{bookoptions}
</Input>
</FormGroup>
<FormGroup row>
<Label htmlFor="roll"> Roll No. of student </Label>
<Input
type="select"
id="roll"
className="form-control"
onInput={(e) => {
this.setState({ roll: e.target.value });
}}
>
{useroptions}
</Input>
</FormGroup>
<FormGroup row>
<Label htmlFor="name"> Name of book </Label>
<Input
type="text"
id="name"
name="name"
placeholder="Name of Book"
defaultValue={defaultBook.name}
value={
!this.state.isbn
? ""
: this.props.books.filter(
(book) => book.isbn === this.state.isbn
)[0].name
}
className="form-control"
disabled
/>
</FormGroup>
<FormGroup row>
<Label htmlFor="author"> Authors </Label>
<Input
type="text"
id="author"
name="author"
placeholder="Name of authors"
defaultValue={defaultBook.author}
value={
!this.state.isbn
? ""
: this.props.books.filter(
(book) => book.isbn === this.state.isbn
)[0].author
}
className="form-control"
disabled
/>
</FormGroup>
<FormGroup row>
<Label htmlFor="name_student"> Name of student </Label>
<Input
type="text"
id="name_student"
name="name_student"
placeholder="Name of student"
defaultValue={
defaultUser.firstname + " " + defaultUser.lastname
}
value={
!this.state.roll
? ""
: this.props.users.filter(
(user) => user.roll === this.state.roll
)[0].firstname +
" " +
this.props.users.filter(
(user) => user.roll === this.state.roll
)[0].lastname
}
className="form-control"
disabled
/>
</FormGroup>
<FormGroup row>
<Label htmlFor="username"> Username of student </Label>
<Input
type="text"
id="username"
name="username"
placeholder="Username of student"
defaultValue={defaultUser.username}
value={
!this.state.roll
? ""
: this.props.users.filter(
(user) => user.roll === this.state.roll
)[0].username
}
className="form-control"
disabled
/>
</FormGroup>
<Row className="align-self-center">
<Col className="text-center">
<Button type="submit" className="bg-primary">
Submit
</Button>
</Col>
</Row>
</Form>
</div>
<br />
</div>
);
}
}
}
export default Issue;
Since the error is reading from undefined, the only possible source of error should be user.roll or defaultUser.roll.
let useroptions = this.props.users.filter((user) => !user.admin);
const defaultUser = useroptions[0];
useroptions = useroptions.map((user, index) => (
<option key={user.roll}>{user.roll}</option>
));
Add an undefined check before using defaultUser and useroptions.
if (defaultUser) {
...
}

TypeError: Cannot set property 'name' of undefined on "onChange" event using React-Sortable-hoc

I'm getting "TypeError: Cannot set property 'name' and 'quantity' of undefined" when I try to input data on any of the input form fields.
This started when I applied the React-Sortable HOC library to be able to drag and drop each list item to sort.
See complete code:
https://codesandbox.io/s/sortable-list-wfpbk?file=/src/AddItem.js
const [inputList, setInputList] = useState([{ name: "", quantity: "" }]);
// handle input change
const handleInputChange = (e, index) => {
const { name, value } = e.target;
const list = [...inputList];
list[index][name] = value;
setInputList(list);
};
const shoppingList = inputList.map((element, i) => {
<div className="form" key={i}>
<input
className="form-field item-form-field"
name="name"
placeholder="Name"
value={element.name}
/>
<input
className="form-field item-form-field"
type="number"
name="quantity"
placeholder="Amount"
// className="ml10"
min="1"
max="12"
value={element.quantity}
></input>
{inputList.length !== 1 && (
<button className="remove-btn remove-btn-3 remove-btn-sep"> Remove</button>
)}
</div>
})
const SortableItem = SortableElement(({value, index}) => (
<div className="form">
<DragHandle />
<input
className="form-field item-form-field"
name="name"
placeholder="Name"
value={value.name}
onChange={(e) => handleInputChange(e, index)}
/>
<input
className="form-field item-form-field"
type="number"
name="quantity"
placeholder="Amount"
min="1"
max="12"
value={value.quantity}
onChange={(e) => handleInputChange(e, index)}
></input>
{inputList.length !== 1 && (
<button className="remove-btn remove-btn-3 remove-btn-sep"
onClick={() => handleRemoveClick(index)}
>
Remove
</button>
)}
</div>
Hey, check out the below codesandbox link, you're issue is fixed.
Link: https://codesandbox.io/s/sortable-list-forked-ne6hp?file=/src/AddItem.js
The issue was with sortableElement, it does not accept index as a prop.
It looks like the index is explicitly omitted in SortableElement.
So, I have passed down another prop with a name like indexTemp={index}.

Not changing values of form reactjs

I have a form in which I am generating form fields dynamically . Now Issue is fields which are not dynamically generated are getting input and those field which are dynamically generated are not taking input in fields. name='name' and name='age' fields are not getting input I cant insert data in them . while first two fields owner and description are working fine
import React from "react";
class Form extends React.Component {
state = {
cats: [{ name: "", age: "" }],
owner: "",
description: ""
};
handleChange = e => {
alert('inot');
if (["name", "age"].includes(e.target.className)) {
let cats = [...this.state.cats];
cats[e.target.dataset.id][
e.target.className
] = e.target.value.toUpperCase();
this.setState({ cats }, () => console.log(this.state.cats));
} else {
this.setState({ [e.target.name]: e.target.value.toUpperCase() });
}
};
addCat = e => {
this.setState(prevState => ({
cats: [...prevState.cats, { name: "", age: "" }]
}));
};
handleSubmit = e => {
e.preventDefault();
};
handleClick = e => document.getElementById(e.target.id).remove();
// changeOption =(e) => {
// this.setState.cats(e.target.value);
// }
render() {
let { owner, description, cats } = this.state;
return (
<form onSubmit={this.handleSubmit} onChange={this.handleChange}>
<div className='row mt-5'>
<div className='col-md-12 mb-5'>
<h3 className='text-center text-primary'>Create Products Option</h3>
</div>
<div className='col-md-3'></div>
<div className='col-md-3'>
<label htmlFor='name'>
<b>Owner</b>
</label>
<input
type='text'
className='form-control'
name='owner'
id='owner'
value={owner}
/>
</div>
<div className='col-md-3'>
<label htmlFor='description'>
<b>Description</b>
</label>
<input
type='text'
className='form-control'
name='description'
id='description'
value={description}
/>
<button
className='btn btn-success rounded-0 w-25 float-right mt-2 shadow-none'
onClick={this.addCat}
>
+
</button>
</div>
<div className='col-md-3'></div>
</div>
{cats.map((val, idx) => {
let catId = `cat-${idx}`,
ageId = `age-${idx}`;
return (
<form onSubmit={this.handleSubmit} onChange={this.handleChange}>
<div id={ageId} key={idx}>
<div className='row mt-5'>
<div className='col-md-3'></div>
<div className='col-md-3'>
<label htmlFor={catId}>
<b>{`Cat #${idx + 1}`}</b>
</label>
<input
type='text'
name='name'
data-id={idx}
id={catId}
value={cats[idx].name}
className='name form-control'
/>
</div>
<div className='col-md-3'>
<label htmlFor={ageId}>
<b>Age</b>
</label>
<input
type='text'
name='age'
data-id={idx}
id={ageId}
value={cats[idx].age}
className='age form-control'
/>
<button
className='btn btn-success rounded-0 w-25 float-right mt-2 shadow-none'
onClick={this.addCat}
>
+
</button>
<input
type='button'
name={ageId}
data-id={idx}
id={ageId}
value={"-"}
className='age float-right mt-2 mr-3 btn btn-danger w-25 rounded-0 w-25 shadow-none'
onClick={this.handleClick}
/>
</div>
<div className='col-md-3'></div>
</div>
</div>
</form>
);
})}
<div className='row mt-3'>
<div className='col-md-3'></div>
<div className='col-md-3'>
<label htmlFor='name'>
<b>Min Selection</b>
</label>
<input
type='text'
className='form-control'
name='min'
id='min'
value={""}
/>
</div>
<div className='col-md-3'>
<label htmlFor='description'>
<b>Max Selection</b>
</label>
<input
type='text'
className='form-control'
name='max'
id='max'
value={""}
/>
<input
className='float-right btn btn-success mt-3'
type='submit'
value='Submit'
/>
{/* <button className="float-right" onClick={this.addCat}>Add new cat</button> */}
</div>
<div className='col-md-3'></div>
</div>
</form>
);
}
}
export default Form;
Codesandbox here. Looks like you should be seeing some errors in your console that might provide some explanation:
Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.
Detailed answer
Working Sandbox here. There are a few things wrong here:
Your handleChange function needs to change
Your function is looking at className which won't work. Your inputs return form-control name for example. Instead try using the element's name.
Updated function:
handleChange = e => {
if (["name", "age"].includes(e.target.name)) {
let cats = [...this.state.cats];
cats[e.target.dataset.id][e.target.name] = e.target.value.toUpperCase();
this.setState({ cats }, () => console.log(this.state.cats));
} else {
this.setState({ [e.target.name]: e.target.value.toUpperCase() });
}
};
Aside
Do not render <form> elements in other <form> elements.
Don't do this. You don't need another form here. Just remove that.
// Line 76-80:
{cats.map((val, idx) => {
let catId = `cat-${idx}`,
ageId = `age-${idx}`;
return (
<form onSubmit={this.handleSubmit} onChange={this.handleChange}>
// ...

How to correctly handle a select dropdown

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>
)
}

Categories

Resources