Ad
React Accessing A Value From An Array
I have a form in React which dynamically adds new input elements. This seems to be working ok but I cant seem to access the input values as shown in this screenshot...
I have tried the following
console.log(this.state.telephone.name)
and...
console.log(this.state.telephone.tidx.name)
where tidx is the unique key.
Here is the constructor...
constructor() {
super();
this.state = {
role: "Installer",
name: "",
telephoneType: [{ name: "" }],
telephone: [{ name: "" }],
tidx: "",
emailType: [{ email: "" }],
email: [{ email: "" }],
eidx: "",
notes: ""
};
}
and this is my function to handle the input forms...
handleTelephoneChange = tidx => evt => {
const newTelephone = this.state.telephone.map((telephone, tsidx) => {
if (tidx !== tsidx) return telephone;
return { ...telephone, name: evt.target.value };
});
this.setState({ telephone: newTelephone }, () => {
// get state on callback
console.log(this.state)
console.log(this.state.telephone.name)
console.log(this.state.telephone.tidx.name)
}
);
};
and rendered like this...
{this.state.telephone.map((telephone, tidx) => (
<MDBRow key={tidx} className="grey-text flex-nowrap align-items-center no-gutters my-2">
<MDBCol md="12">
<input value={telephone.name} onChange={this.handleTelephoneChange(tidx)}placeholder={`Telephone No. #${tidx + 1}`} className="form-control"/>
</MDBCol>
</MDBRow>
))}
Any advice greatly appreciated as I am fairly new to forms in React. Thanks.
Ad
Answer
telephone
is an array, so you should be using index notation.
console.log(this.state.telephone[tidx].name)
To render a corresponding phone-type for each telephone:
{this.state.telephone.map((telephone, tidx) => (
<MDBRow key={tidx} className="grey-text flex-nowrap align-items-center no-gutters my-2">
<MDBCol md="12">
<input value={this.state.telephoneType[tidx].yourValue} onChange={this.defineYourTelephoneTypeEventHandler(tidx)}/>
<input value={telephone.name} onChange={this.handleTelephoneChange(tidx)}placeholder={`Telephone No. #${tidx + 1}`} className="form-control"/>
</MDBCol>
</MDBRow>
))}
Ad
source: stackoverflow.com
Related Questions
- → How do I create an array from a single form input box with php on octobercms?
- → Print the output value of an array in twig [OctoberCMS]
- → Declare an array variable to the controller/component [Laravel, October CMS]
- → Removing a JavaScript property inside a specific Object within an Array
- → Javascript loop indexing issue
- → search array without duplicates React.js
- → Populating array with items from different HTML attributes
- → Get all index value of 1 from binary "01000111"
- → Remove objects from array - Two different approaches, two different results when consulting the length of each array
- → Compare values in two arrays
- → adding multiple polygons in google maps using loops and arrays
- → .split() JS not "splitting" correctly?
- → Vue.js - Binding radio elements of same name to array
Ad