Im only getting the username and password field? React - reactjs

Im trying to use post data but the only thing im getting back from the form is the username and password, What am i doing wrong? i want to get the teacher data too inside the state like fname, lname, mname etc. Also why is it only the username and password is getting posted or serialized. Thanks so much in advance
class Teachers extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedData: {},
tableData: [{
id: '',
email: '',
password: '',
}],
username: '',
password: '',
teacher: [{
employeeNo:'',
prefixName: '',
fname: '',
lname: '',
middleInitial: '',
sex: '',
citizenship: '',
status: '',
permanentAddress: '',
presentAddress: '',
bday: '',
contactNo: '',
emailAdd: '',
emergencyContactNo: '',
}],
}
this.editedData = params => {
console.log(params);
};
this.toggleModal = this.toggleModal.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.addNotification = this.addNotification.bind(this);
this.handleChange = this.handleChange.bind(this);
}
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
};
//request the token
async handleSubmit(event) {
event.preventDefault();
const getCred = await fetch('http://tfismartasp-001-site10.btempurl.com/api/Teacher/Register', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'ApiKey': "Secret"
},
method: "POST",
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
prefixName: this.state.teacher.prefixName,
fname: this.state.teacher.fname,
lname: this.state.teacher.lname,
middleInitial: this.state.teacher.middleInitial,
sex: this.state.teacher.sex,
citizenship: this.state.teacher.citizenship,
status: this.state.teacher.Status,
permanentAddress: this.state.teacher.permanentAddress,
PresentAddress: this.state.teacher.presentAddress,
bday: this.state.teacher.bday,
contactNo: this.state.teacher.contactNo,
emailAdd: this.state.teacher.emailAdd,
emergencyContactNo: this.state.teacher.emergencyContactNo,
}),
});
const data = await getCred.json();
console.log(data);
}
<Modal isOpen={this.state.modalDialog} className="modal-lg" fade={false} toggle={() => this.toggleModal("modalDialog")}>
<ModalHeader toggle={() => this.toggleModal("modalDialog")}>
Edit Profile
</ModalHeader>
<form className="margin-bottom-0" onSubmit={this.handleSubmit}>
<ModalBody>
<h3><label className="control-label">Personal Information </label></h3>
<label className="control-label">Name <span className="text-danger">*</span></label>
<div className="row row-space-10">
<div className="col-md-2 m-b-15">
<input type="text" className="form-control" placeholder="Prefix" name="prefixName" value={this.state.teacher.prefixName} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<input type="text" className="form-control" placeholder="First name" name="fname" value={this.state.teacher.fname} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<input type="text" className="form-control" placeholder="Last name" name="lname" value={this.state.teacher.lname} onChange={this.handleChange} required="" />
</div>
<div className="col-md-2 m-b-15">
<input type="text" className="form-control" placeholder="Middle name" name="middleInitial" value={this.state.teacher.middleInitial} onChange={this.handleChange} required="" />
</div>
</div>
<div className="row row-space-10">
<div className="col-md-4 m-b-15">
<label className="control-label">Gender <span className="text-danger">*</span></label>
<select className="form-control" name="sex">
<option value={this.state.teacher.sex} onChange={this.handleChange}>MALE</option>
<option value={this.state.teacher.sex} onChange={this.handleChange}>FEMALE</option>
</select>
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Birthdate <span className="text-danger">*</span></label>
<input type="date" className="form-control" placeholder="Birthdate" name="bday" value={this.state.teacher.bday} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Citizenship <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Citizenship" name="citizenship" value={this.state.teacher.citizenship} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Status <span className="text-danger">*</span></label>
<select className="form-control" name="status" placeholder="status" >
<option value={this.state.teacher.status} onChange={this.handleChange}>Single</option>
<option value={this.state.teacher.status} onChange={this.handleChange}>Married</option>
</select>
</div>
</div>
<hr/>
<h3><label className="control-label">Account Information </label></h3>
<div className="row row-space-10">
<div className="col-md-4 m-b-15">
<label className="control-label">Employee Number <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Employee No." name="employeeNo" value={this.state.teacher.employeeNo} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Username <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Username" name="username" value={this.state.username} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Password <span className="text-danger">*</span></label>
<input type="password" className="form-control" placeholder="Password" name="password" value={this.state.password} onChange={this.handleChange} required="" />
</div>
</div>
<hr/>
<h3><label className="control-label">Contact Information </label></h3>
<div className="row row-space-10">
<div className="col-md-4 m-b-15">
<label className="control-label">Permanent Address <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Permamnent Address" name="permanentAddress" value={this.state.teacher.permanentAddress} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Present Address <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Present Address" name="presentAddress" value={this.state.teacher.presentAddress} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Contact Number <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Contact No." name="contactNo" value={this.state.teacher.contactNo} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Email Address <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Email Address" name="emailAdd" value={this.state.teacher.emailAdd} onChange={this.handleChange} required="" />
</div>
<div className="col-md-4 m-b-15">
<label className="control-label">Emergency Number <span className="text-danger">*</span></label>
<input type="text" className="form-control" placeholder="Emergency No." name="emergencyContactNo" value={this.state.teacher.emergencyContactNo} onChange={this.handleChange} required="" />
</div>
</div>
</ModalBody>
<ModalFooter>
<button onClick={() => {
this.addNotification('success', 'Success', 'All data has been successfully saved', 'bottom-right')
this.toggleModal("modalDialog")
}} className="btn btn-sm btn-success">Save</button>
<button
className="btn btn-white btn-sm"
onClick={() => this.toggleModal("modalDialog")} >
Close
</button>
</ModalFooter>
</form>
</Modal>

If you are talking about only one teacher object, you can change the teacher to an object. Just remove [ and ] between the teacher object.

Related

Show or hide on multiple element using class in React

I am using the class component here Consider selecting Yes or No value depending on whether to show or hide the div.
I wanted to do the same thing with multiple div. But here if I am selecting yes then both the div are open. And not close to clicked on no value.
Here is my code:
class PersonalInfo extends Component {
constructor(props) {
super(props);
this.divstatus1 = this.divstatus1.bind(this);
this.divstatus2 = this.divstatus2.bind(this);
this.state = {
value1: 'no',
value2: 'no'
};
}
divstatus1 = (e) => {
this.setState({ value1: e.target.value1 });
}
divstatus2 = (e) => {
this.setState({ value2: e.target.value2 });
}
render() {
return (
<div>
<h3 className="showbase_header">Passport Details</h3>
<div className="form-group">
<label htmlFor="orderby"> Do you have passport ?</label>
<select className="form-control orderby" onChange={this.divstatus1}>
<option value="" selected>Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<br></br>
<div className={this.state.value1} >
<div className="row">
<div className="col-md-6 form-group">
<label htmlFor="name">Passport Number
<span className="required">*</span>
</label>
<input type="text" id="firstname" aria-required="true" size={30} name="firstname" className="form-control" placeholder="" />
</div>
<div className="col-md-6 form-group">
<label htmlFor="name">Place Of Issue
<span className="required">*</span>
</label>
<input type="text" id="lastname" aria-required="true" size={30} name="lastname" className="form-control" placeholder="" />
</div>
</div>
<div className="row">
<div className="col-sm-6 form-group">
<label htmlFor="expirydate">Expiry Date
<span className="required">*</span>
</label>
<input type="date" id="expirydate" aria-required="true" size={30} name="expirydate" className="form-control" placeholder="" />
</div>
<div className="col-sm-6 form-group">
<label htmlFor="issuedate">Issue Date
<span className="required">*</span>
</label>
<input type="date" id="issuedate" aria-required="true" size={30} name="issuedate" className="form-control" placeholder="" />
</div>
</div>
</div>
</div>
<div className="form-group">
<h3 className="showbase_header">Representation</h3>
<select className="form-control orderby" onChange={this.divstatus2}>
<option value="">Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select><br />
<div className={this.state.value2} >
<div class="row">
<div className="col-sm-6 form-group">
<label htmlFor="name">Name
<span className="required">*</span>
</label>
<input type="text" id="name" aria-required="true" size={30} name="name" className="form-control" placeholder="" />
</div>
<div className="col-sm-6 form-group">
<label htmlFor="number">Contact Number
<span className="required">*</span>
</label>
<input type="number" id="name" aria-required="true" size={30} name="number" className="form-control" placeholder="" />
</div>
</div>
</div>
</div>
</div>
);
}
}
export default PersonalInfo;
I have added in main.css
.yes{display: block;}
.no{display: none;}
Can you try this,
divstatus1 = (e) => {
this.setState({ value1: e.target.value });
}
divstatus2 = (e) => {
this.setState({ value2: e.target.value });
}
option does not have an attribute called value1 or value2

How to set state value in each in each input field via get method

I have an React form with 10 input field.I have a below code to set state for each field and finally I have submit this state to database.(insert record in table using post method via state).I would like to know how to set value in each in each input field via get method.
initial State :-
this.state = {
UserId : this.props.match.params.id,
FirstName: '',
LastName : '',
EmailId : '',
MobileNo : '',
DivisionId :'',
UserName : '',
Password : '',
ConfirmPassword : '',
RoleId : '',
UpdateUserName : localStorage.getItem("UserId"),
GridState : []
};
Setting State Value in each input Field before submitting :-
onChangeHandler = (event) => {
let nam = event.target.name;
let val = event.target.value;
this.setState({[nam]: val});
}
Submit Record to Database via Post Method :-
onSubmitHandler = (event) => {
axios.post(ConfigItem[0].APIPath+'Users/',this.state)
.then(res => {
this.props.history.push('/UserList')
})
}
Get inserted record from API via get method :-
axios.get(ConfigItem[0].APIPath+'users/' + this.props.match.params.id)
.then(res => {
console.log(res.data.data); ***// I would like to know how to set value in each input field***
HTML render :-
render() {
return (
<form onSubmit={this.onSubmitHandler}>
<div className="animated fadeIn">
<Row>
<Col xs="12" sm="12">
<Card>
<CardHeader>
<Row>
<Col xs="8" sm="8">
<strong> <i> User Creation Entry </i> </strong>
</Col>
<Col xs="4" sm="4">
<Button type="button" text="Back" size="sm" onClick={this.onBackButtonClick} color="danger" className="pull-right ml-1 "><i className="fa fa-ban"></i> Back</Button>
<Button type="submit" size="sm" color="success" className="pull-right ml-1 "><i className="fa fa-dot-circle-o"></i> Save</Button>
</Col>
</Row>
</CardHeader>
<CardBody>
<div className="form-group row">
<label className="col-sm-1 col-form-label col-form-label-sm">First Name</label>
<div className="col-sm-3">
<input type="text" name="FirstName" className="form-control form-control-sm" id="TxtFirstName" placeholder="First Name" required onChange={this.onChangeHandler}/>
</div>
<label className="col-sm-1 col-form-label col-form-label-sm">Last Name</label>
<div className="col-sm-3">
<input type="text" name="LastName" className="form-control form-control-sm" id="TxtLastName" placeholder="Last Name" required onChange={this.onChangeHandler}/>
</div>
<label className="col-sm-1 col-form-label col-form-label-sm">Email Id</label>
<div className="col-sm-3">
<input type="email" name ="EmailId" className="form-control form-control-sm" id="TxtEmailId" placeholder="EmailId" required onChange={this.onChangeHandler}/>
</div>
</div>
<div className="form-group row">
<label className="col-sm-1 col-form-label col-form-label-sm">Mobile No</label>
<div className="col-sm-3">
<input type="text" name ="MobileNo" className="form-control form-control-sm" id="TxtMobileNo" placeholder="Mobile No" onChange={this.onChangeHandler} />
</div>
<label className="col-sm-1 col-form-label col-form-label-sm">Division</label>
<div className="col-sm-3">
<select name ="DivisionId" className="form-control" required onChange={this.onChangeHandler}>
{DivisionList}
</select>
</div>
<label className="col-sm-1 col-form-label col-form-label-sm">User Name</label>
<div className="col-sm-3">
<input type="text" name ="UserName" className="form-control form-control-sm" id="TxtUserName" placeholder="User Name" required onChange={this.onChangeHandler}/>
</div>
</div>
<div className="form-group row">
<label className="col-sm-1 col-form-label col-form-label-sm">Password</label>
<div className="col-sm-3">
<input type="password" name ="Password" className="form-control form-control-sm" id="TxtPassword" placeholder="Password" required onChange={this.onChangeHandler}/>
</div>
<label className="col-sm-1 col-form-label col-form-label-sm">Confirm</label>
<div className="col-sm-3">
<input type="password" name="ConfirmPassword" className="form-control form-control-sm" id="TxtConfirm" placeholder="Confirm Password" required onChange={this.onChangeHandler}/>
</div>
<label className="col-sm-1 col-form-label col-form-label-sm">Role</label>
<div className="col-sm-3">
<select name ="RoleId" data-show-subtext="true" data-live-search="true" className="form-control selectpicker" id="CboRole" required onChange={this.onChangeHandler}>
{RoleList}
</select>
</div>
</div>
</CardBody>
<CardFooter>
<div id="data-grid-demo">
<DataGrid
dataSource={this.state.GridState}
ref={ref => this.dataGrid = ref}
keyExpr="MenuId"
showBorders={true}
onToolbarPreparing={this.onToolbarPreparing}
onRowUpdated={this.onRowUpdated}
>
<Paging enabled={false} />
<Editing
mode="batch"
allowUpdating={true}
selectTextOnEditStart={true}
startEditAction='click' />
<Column dataField="UserAccessId" visible={false} />
<Column dataField="MenuId" visible={false} />
<Column dataField="Menu" />
<Column dataField="SubMenu" />
<Column dataField="ViewAccess" caption="ViewAccess" dataType="boolean" >
<CheckBox defaultValue={false} />
</Column>
<Column dataField="ZohoParameter" />
<Column dataField="Remarks" />
</DataGrid>
</div>
</CardFooter>
</Card>
</Col>
</Row>
</div>
</form>
);
}
Set the value to each <input /> that is equal to the class state, for example:
<input type="text" name="FirstName" className="form-control form-control-sm" id="TxtFirstName" value={this.state.FirstName} placeholder="First Name" required onChange={this.onChangeHandler}/>
After that, simply save your data from the axios call into the state:
this.setState({
FirstName: result.data.FirstName,
//Add the others by yourself
})
If your query result properties have the same name as the ones in your state, you could simply do:
this.setState({
...result.data.data //depending on your result object structure
})
the second statement is not working,please check my below result of json data and advise how to do this..
[{"UserId":2009,"FirstName":"jj","LastName":"kk","EmailId":"kk.biz#itytu.com","MobileNo":"9789684772","DivisionId":4,"UserName":"khizer11","Password":"$2b$10$JRG/Zp5TQOJkZPIj2bXFset3gx8DF/OFnrGzZqR4rnC7Bc/a9.yyO","DPassword":"ii#123","RoleId":8,"LoginTag":null,"LoginTime":null,"LogOutTime":null,"SysName":"DELLNETBOOK","UpdateUserName":"","UpdateSysName":null,"UpdateDateTime":null,"DefaultDateTime":

React conditional divs with hooks

I am creating a signup form that will render differently depending on whether the person signing up chooses Post a project or Work on a project from the very first div in the form.
How can I render each div that follows in the form-group conditionally based on what is selected in the first div? I am using hooks and I have found that most examples are for the extends Component approach.
My form:
const signUpForm = () => (
<form onSubmit={clickSubmit}>
<div className="form-group">
<select onChange={handleChange("role")} class="form-control">
<option selected>I want to...</option>
<option>Post a project</option>
<option>Work on a project</option>
</select>
</div>
<div className="form-group">
<input
onChange={handleChange("name")}
type="text"
placeholder="Name"
className="form-control"
value={name}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("email")}
type="email"
placeholder="Email"
className="form-control"
value={email}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("password")}
type="password"
placeholder="Password"
className="form-control"
value={password}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("studying")}
type="text"
placeholder="I'm studying..."
className="form-control"
value={studying}
/>
</div>
<div>
<div>{createInputs()}</div>
<button
className="btn btn-outline-primary btn-sm mb-3"
onClick={addSkill}
type="text"
>
Add more skills
</button>
</div>
<button onClick={clickSubmit} className="btn btn-primary" type="submit">
Sign Up
</button>
</form>
);
State:
const Signup = () => {
const [values, setValues] = useState({
name: "",
email: "",
password: "",
studying: "",
skills: [""],
error: "",
success: "",
role: ""
});
const { name, email, password, studying, skills, success, error, role } = values;
handleChange():
const handleChange = name => event => {
setValues({ ...values, error: false, [name]: event.target.value });
};
You should first divide the signUp in two parts and then call second function based on value of "role" from state.
The idea is to return the divs from second function based on state of first input.
const signUpForm = () => (
<form onSubmit={clickSubmit}>
<div className="form-group">
<select onChange={handleChange("role")} class="form-control">
<option selected>I want to...</option>
<option>Post a project</option>
<option>Work on a project</option>
</select>
</div>
{this.renderInput()}
<button onClick={clickSubmit} className="btn btn-primary" type="submit">
Sign Up
</button>
</form>
);
renderInput() {
if (values.role === "post") {
return (
<div className="form-group">
<input onChange={handleChange("name")} type="text" placeholder="Name" className="form-control" value={name} />
</div>
<div className="form-group">
<input onChange={handleChange("email")} type="email" placeholder="Email" className="form-control" value={email} />
</div>
<div className="form-group">
<input onChange={handleChange("password")} type="password" placeholder="Password" className="form-control" value={password} />
</div>
<div className="form-group">
<input onChange={handleChange("studying")} type="text" placeholder="I'm studying..." className="form-control" value={studying} />
</div>
<div>
<div>{createInputs()}</div>
<button className="btn btn-outline-primary btn-sm mb-3" onClick={addSkill} type="text">
Add more skills
</button>
</div>
);
}
}
You want to test the role state value is truthy/falsey and render the rest of your form on that value.
const SignUpForm = () => (
<form onSubmit={clickSubmit}>
<div className="form-group">
<select
defaultValue='unselected' // set default value here
onChange={handleChange("role")}
className="form-control" // fix className here, class alone isn't correct in react
>
<option value='unselected'>I want to...</option>
<option value='post'>Post a project</option>
<option value='work'>Work on a project</option>
</select>
</div>
{!!role && (
<Fragment>
<div className="form-group">
<input
onChange={handleChange("name")}
type="text"
placeholder="Name"
className="form-control"
value={name}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("email")}
type="email"
placeholder="Email"
className="form-control"
value={email}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("password")}
type="password"
placeholder="Password"
className="form-control"
value={password}
/>
</div>
<div className="form-group">
<input
onChange={handleChange("studying")}
type="text"
placeholder="I'm studying..."
className="form-control"
value={studying}
/>
</div>
<div>
<div>{createInputs()}</div>
<button
className="btn btn-outline-primary btn-sm mb-3"
onClick={addSkill}
type="text"
>
Add more skills
</button>
</div>
</Fragment>
)}
<button onClick={clickSubmit} className="btn btn-primary" type="submit">
Sign Up
</button>
</form>
);

How to assign value from array to model

I have problem with assign from array to model. I want to assign firstName value from userFromDb and assign this value to firstName in model and the same with another values. I don't know how do this :(
User
export interface User{
id:string;
firstName:string;
lastName:string;
email:string;
password:string;
}
UpadateUserComponent.ts
userFromDb: Array<Object>;
model:User = {
id: '',
firstName: '',
lastName: '',
email: '',
password: ''}
ngOnInit() {
let id = this.route.snapshot.paramMap.get('id');
this.userService.getUser(id).subscribe(result => {
console.log(result)
this.userFromDb = result
console.log(this.userFromDb)
});
UpadateUserComponent.html
<div>
<form action="" #f="ngForm" (ngSubmit)="saveUser()" novalidate>
<div>
<label for="firstName">First Name: </label>
<input [(ngModel)]="model.firstName" type="text" id="firstName" name="firstName" placeholder="Name">
</div>
<div>
<label for="lastName">Last Name: </label>
<input [(ngModel)]="model.lastName" type="text" id="lastName" name="lastName" placeholder="Name" >
</div>
<div>
<label for="email">Email: </label>
<input [(ngModel)]="model.email" type="text" id="email" name="email" placeholder="Name" >
</div>
<div>
<label for="password">Password: </label>
<input [(ngModel)]="model.password" type="text" id="password" name="password" placeholder="Name" >
</div>
<button type="submit">Submit</button>
</form>
</div>
I do not know what your database structure looks like, but lets say it is the same as your frontend...
First I am not sure why your userFromDb is an array, would it return more than one user?
If you just want to insert the values then the simplest would be:
this.userService.getUser(id).subscribe(result => {
console.log(result)
this.userFromDb = result
this.model.firstName = this.userFromDB[0].firstName
// same with other values here
console.log(this.userFromDb)
});
this.userService.getUser(id).subscribe(result => {
console.log(result);
this.userFromDb:User = result[0];
console.log(this.userFromDb);
});
HTML
<div>
<form action="" #f="ngForm" (ngSubmit)="saveUser()" novalidate>
<div>
<label for="firstName">First Name: </label>
<input [(ngModel)]="userFromDb.firstName" type="text" id="firstName" name="firstName" placeholder="Name">
</div>
<div>
<label for="lastName">Last Name: </label>
<input [(ngModel)]="model.lastName" type="text" id="lastName" name="lastName" placeholder="Name" >
</div>
<div>
<label for="email">Email: </label>
<input [(ngModel)]="userFromDb.email" type="text" id="email" name="email" placeholder="Name" >
</div>
<div>
<label for="password">Password: </label>
<input [(ngModel)]="userFromDb.password" type="text" id="password" name="password" placeholder="Name" >
</div>
<button type="submit">Submit</button>
</form>
</div>

How to bind value from dropdown list in React?

I'm trying to get the value of the id in my dropdown list to post to an API and i'm not entirely sure how to do that.I Any help would be appreciated
I've tried using the onchange with a handleChange function but it doesn't do anything. The react files are below for the form and for posting of the form
import React from "react";
import { updateUsers, fetchUsers } from "./actions/appactions";
import FormChange from "./formchange";
var createReactClass = require("create-react-class");
const Update = createReactClass({
getIntitialState() {
return {
users: []
};
},
componentWillReceiveProps(props) {
this.setState(props);
},
componentDidMount() {
fetchUsers(this.props.match.params.usersId)
.then(resp => resp.json())
.then(data => {
// this.setState({
// users: data
// });
this.setState(state => {
state.users = data;
return state;
});
})
.catch(err => {
console.error("error", err);
});
},
handleSubmit(data) {
updateUsers(this.state.users.id, data);
},
render() {
return (
<div>
<FormChange
onSubmit={this.handleSubmit}
password={this.state.users.password}
/>
</div>
);
}
});
export default Update;
import React from "react";
import { Link } from "react-router-dom";
var createReactClass = require("create-react-class");
const Form2 = createReactClass({
//setting initial state
getInitialState() {
return {
customerName: this.props.customerName,
email: this.props.email,
businessName: this.props.businessName,
address: this.props.address,
city: this.props.city,
lga: this.props.lga,
url: this.props.url,
description: this.props.description,
obj: []
};
},
componentDidMount() {
this.fetchOptions();
},
fetchOptions() {
fetch("https://localhost:44341/api/categories")
.then(res => res.json())
.then(json => {
this.setState({
obj: json
});
});
},
handleCustomerChange(e) {
this.setState({
customerName: e.target.value
});
},
handleEmailChange(e) {
this.setState({
email: e.target.value
});
},
handleBusinessChange(e) {
this.setState({
businessName: e.target.value
});
},
handleAddressChange(e) {
this.setState({
address: e.target.value
});
},
handleCityChange(e) {
this.setState({
city: e.target.value
});
},
handleLgaChange(e) {
this.setState({
lga: e.target.value
});
},
handleUrlChange(e) {
this.setState({
url: e.target.value
});
},
handleDescriptionChange(e) {
this.setState({
description: e.target.value
});
},
handleCatChange(e) {
this.setState({
obj: e.target.value
});
},
handleSubmit(e) {
e.preventDefault();
this.props.onSubmit(this.state);
},
render() {
return (
<form
name="categories_post"
className="form-horizontal"
onSubmit={this.handleSubmit}
>
<div id="business_post">
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="customerName"
>
Customer Name
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.customerName}
onChange={this.handleCustomerChange}
id="customerName"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label required" htmlFor="email">
Email
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.email}
onChange={this.handleEmailChange}
id="email"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="businessName"
>
Business Name
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.businessName}
onChange={this.handleBusinessChange}
id="businessName"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="address"
>
Address
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.address}
onChange={this.handleAddressChange}
id="address"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label required" htmlFor="city">
City
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.city}
onChange={this.handleCityChange}
id="city"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label required" htmlFor="lga">
LGA
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.lga}
onChange={this.handleLgaChange}
id="lga"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label required" htmlFor="url">
URL
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.url}
onChange={this.handleUrlChange}
id="url"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="description"
>
Description
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.description}
onChange={this.handleDescriptionChange}
id="description"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label required" htmlFor="email">
categories name
</label>
<div className="drop-down">
<select>
{this.state.obj.map(obj => {
return (
<option key={obj.id} value={obj.id}>
{obj.categoryName}
</option>
);
})}
</select>
</div>
</div>
<div className="form-group">
<div className="col-sm-2" />
<div className="col-sm-10">
<button
type="submit"
id="categoriesSubmit"
className="btn btn-default"
>
submit
</button>
</div>
</div>
<div className="form-group">
<div className="col-sm-2" />
<div className="col-sm-10">
<button className="btn btn-danger .mt-3">
<Link to="/business">Home</Link>
</button>
</div>
</div>
</div>
</form>
);
}
});
export default Form2;
UPDATE
Use react-select, It is able to handle id and value elegantly.
Can you give it a try?
npm install react-select
import React from "react";
import { Link } from "react-router-dom";
var createReactClass = require("create-react-class");
import Select from 'react-select';
const Form2 = createReactClass({
//setting initial state
getInitialState() {
return {
customerName: this.props.customerName,
email: this.props.email,
businessName: this.props.businessName,
address: this.props.address,
city: this.props.city,
lga: this.props.lga,
url: this.props.url,
description: this.props.description,
obj: []
};
},
componentDidMount() {
this.fetchOptions();
},
fetchOptions() {
fetch("https://localhost:44341/api/categories")
.then(res => res.json())
.then(json => {
this.setState({
obj: json
});
});
},
handleCustomerChange(e) {
this.setState({
customerName: e.target.value
});
},
handleEmailChange(e) {
this.setState({
email: e.target.value
});
},
handleBusinessChange(e) {
this.setState({
businessName: e.target.value
});
},
handleAddressChange(e) {
this.setState({
address: e.target.value
});
},
handleCityChange(e) {
this.setState({
city: e.target.value
});
},
handleLgaChange(e) {
this.setState({
lga: e.target.value
});
},
handleUrlChange(e) {
this.setState({
url: e.target.value
});
},
handleDescriptionChange(e) {
this.setState({
description: e.target.value
});
},
handleCatChange(e) {
this.setState({
obj: e.target.value
});
},
handleSubmit(e) {
e.preventDefault();
this.props.onSubmit(this.state);
},
handleChange = (selectedOption) => {
// this.setState({ selectedOption }); add it to state
console.log(`Option selected:`, selectedOption);
},
render() {
return (
<form
name="categories_post"
className="form-horizontal"
onSubmit={this.handleSubmit}
>
<div id="business_post">
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="customerName"
>
Customer Name
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.customerName}
onChange={this.handleCustomerChange}
id="customerName"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label required" htmlFor="email">
Email
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.email}
onChange={this.handleEmailChange}
id="email"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="businessName"
>
Business Name
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.businessName}
onChange={this.handleBusinessChange}
id="businessName"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="address"
>
Address
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.address}
onChange={this.handleAddressChange}
id="address"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label required" htmlFor="city">
City
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.city}
onChange={this.handleCityChange}
id="city"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label required" htmlFor="lga">
LGA
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.lga}
onChange={this.handleLgaChange}
id="lga"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label required" htmlFor="url">
URL
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.url}
onChange={this.handleUrlChange}
id="url"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label
className="col-sm-2 control-label required"
htmlFor="description"
>
Description
</label>
<div className="col-sm-10">
<input
type="text"
value={this.state.description}
onChange={this.handleDescriptionChange}
id="description"
required="required"
className="form-control"
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label required" htmlFor="email">
categories name
</label>
<div className="drop-down">
<Select
value={selectedOption}
onChange={this.handleChange}
options={this.state.obj}
/>
</div>
</div>
<div className="form-group">
<div className="col-sm-2" />
<div className="col-sm-10">
<button
type="submit"
id="categoriesSubmit"
className="btn btn-default"
>
submit
</button>
</div>
</div>
<div className="form-group">
<div className="col-sm-2" />
<div className="col-sm-10">
<button className="btn btn-danger .mt-3">
<Link to="/business">Home</Link>
</button>
</div>
</div>
</div>
</form>
);
}
});
export default Form2;
react-select docs
I've solved it
//handlecatchange
handleCatChange() {
var value = ReactDOM.findDOMNode(this.refs.categoryId).value;
this.setState({
categoryId: parseInt(value)
});
},
the dropdown list
<div className="drop-down">
{/* <Select value={selectedOption} onChange={this.handleChange} options={this.state.obj}></Select> */}
<select ref="categoryId" onChange={this.handleCatChange}>
{this.state.obj.map(obj => {
return (
<option
key={obj.id}
value={obj.id}
onChange={this.handleCatChange}
>
{obj.categoryName}
</option>
);
})}
</select>
</div>

Resources