cannot update field on Change - reactjs

i have 3 update textfields, the value of which is coming from a state called edit_obj, like so:
<input type="text" noValidate name="uname_edit" value={this.state.edit_obj.username} onChange={e => this.editchangeHandler(e)} />
when i click on 'edit' button, editClick function works that sets the value of edit_obj like so:
this.setState({edit_obj: editval})
I am attaching the full code. Please let me know how i can edit the value d the textfield:
import React from 'react';
import {FromErrors1} from './formErrors';
import { SlowBuffer } from 'buffer';
class Form extends React.Component{
constructor(props){
super(props);
this.state={
uname: '',
pass: '',
address:'',
salary:'',
addFormValues:{
username:'',
password:'',
address:''
},
errorfields:{
uname_err:'',
pass_err:'',
address_err:'',
salary_err:'',
valid_user:false,
valid_pass:false,
valid_address:false,
valid_salary:false,
},
delete_data:[],
edit_showui:false,
edit_obj:{},
editval:{},
edit_data:[],
editted_uname:''
}
this.changeHandler= this.changeHandler.bind(this)
this.pushAddStudentData=new Array()
this.submitForm= this.submitForm.bind(this);
//this.editchangeHandler = this.editchangeHandler.bind(this)
//this.editClick = this.editClick.bind(this)
}
editClick =(that,editval) =>{
//alert("du")
//show edit ui:
this.setState({edit_showui:true});
//add values to the inputs of show ui
console.log('editval: ',editval);
//this.setState({edit_obj:editval});
//this.setState({edit_data:this.state.edit_data.push(editval)});
/*this.setState((state)=>({
edit_data:state.edit_data.push(editval)
}))*/
this.state.edit_data=[]
this.setState(prevState => ({
edit_data: [...prevState.edit_data, editval]
}))
this.setState({edit_obj: editval})
console.log("edit_obj:::::::",this.state.edit_obj)
}
editchangeHandler = (e) =>{
console.log('ename::',e.target.name)
console.log('etarget::',e.target.value)
//this.setState({[e.target.name]:e.target.value})
console.log('edit_obj::',this.state.edit_obj)
//newEditVal
//this.state.newEditVal.username =
/*
if(e.target.name=='uname_edit'){
console.log('uname_edit')
//editted_uname
this.setState(
{editted_uname : ''}
)
console.log('editted_uname::',this.state.editted_uname)
}
if(e.target.name=='pass_edit'){
console.log('pass_edit')
}
if(e.target.name=='address_edit'){
console.log('address_edit')
}
*/
//this.setState({})
this.setState({
[e.target.name]: e.target.value
});
}
updateval=()=>{
console.log('EDIT_OBJ: ',this.state.edit_obj)
}
deleteClick =(e,f) =>{
console.log("sefr",e,'a::',f);
// if(this.pushAddStudentData.indexOf(f) > -1){
// }
let finaldeleteddata=[];
for( var i = 0; i < this.state.delete_data.length; i++){
console.log('this.state.delete_data[i]===f:: ',this.state.delete_data[i]===f)
console.log('and f:: ',f)
if ( this.state.delete_data[i] === f) {
this.state.delete_data.splice(i, 1);
// this.setState(
// {
// delete_data:finaldeleteddata
// }
// )
this.setState(prevState => ({
delete_data: [...prevState.delete_data]
}))
}
console.log('YEYEYEYEEDITDATATAa:: ',this.state.delete_data)
console.log("finaldeleteddata:: ",finaldeleteddata)
}
}
changeHandler = (ev) =>{
// alert("gugugu")
this.setState({[ev.target.name]:ev.target.value})
console.log(this.state)
}
submitForm = (e) =>{
let finaladdeddata;
e.preventDefault();
console.log('this.state.uname:',this.state.uname);
console.log('this.state.pass:',this.state.pass);
let usererror = {...this.state.errorfields};
var regex_username = new RegExp(/^[a-zA-Z ]*$/);
if(this.state.uname && regex_username.test(this.state.uname)){
//no error
// this.state.valid_user= true; /THIS IS NOT RIGHT WAY, USE THIS.SETSTATE
alert("iffff");
usererror.uname_err='';
usererror.valid_user = true
console.log("usererror::",usererror)
console.log("this.STATEuserif:::",this.state.errorfields.valid_user)
this.setState({errorfields: usererror});
}else{
//else of user
alert('2user')
console.log('usererror: ',usererror)
usererror.uname_err= 'username not valid';
usererror.valid_user = false;
this.setState({errorfields: usererror});
//there is error
console.log("this.STATEuserelse:::",this.state)
}
if(this.state.pass && this.state.pass.length <=6){
//if of pass
//no error
// this.state.valid_pass= true;
usererror.valid_pass=true;
usererror.pass_err='';
this.setState({errorfields:usererror})
console.log("this.STATEpassif:::",this.state)
}else{
//else of pass
alert('2pass')
usererror.valid_pass=false;
usererror.pass_err='invalid password | password length more than 6';
this.setState({errorfields:usererror})
//there is error
console.log('this.state.errorfields',this.state.errorfields)
console.log("this.STATE2:::",this.state)
}
//usererror
//errorfields
console.log("address:", this.state.address)
console.log("salary:", this.state.salary)
//put error fields in address
if(this.state.address && this.state.address.length<=20){
// this.state.valid_address=true;
usererror.address_err='';
usererror.valid_address=true
this.setState({errorfields:usererror})
} else{
usererror.address_err='Empty address | address length more than 20';
usererror.valid_address=false
this.setState({errorfields:usererror})
}
/*form={}
uname: '',
pass: '',
address:''
}*/
console.log('usererror.valid_address',usererror.valid_address);
console.log('usererror.valid_pass',usererror.valid_pass);
console.log('usererror.valid_user',usererror.valid_user);
if(usererror.valid_address==true && usererror.valid_pass==true && usererror.valid_user==true){
alert("YESSS");
let addFormValues_dupl= {...this.state.addFormValues};
addFormValues_dupl.username = this.state.uname;
addFormValues_dupl.password = this.state.pass;
addFormValues_dupl.address = this.state.address;
console.log('addFormValues_dupl',addFormValues_dupl);
// this.pushAddStudentData.push(addFormValues_dupl)
//this.setState({delete_data:addFormValues_dupl})
this.state.delete_data.push(addFormValues_dupl)
console.log('state',this.state);
// this.setState({addFormValues: this.state.uname})
}else{
alert("NOOO")
//this.pushAddStudentData=[]
console.log('pushAddStudentDataELSE',this.pushAddStudentData[0]);
}
}
render(){
return(
<div>
<h2>Add Employee info</h2>
<div className="displayerrors">
{/* <ul>{this.state.errorfields.map((a,i)=>{<li>a</li>})}</ul> */}
<input type="hidden" value={this.state.errorfields}/>
<p>{this.state.errorfields.uname_err} - {this.state.errorfields.valid_user}</p>
<p>{this.state.errorfields.pass_err}</p>
<p>{this.state.errorfields.address_err}- {this.state.errorfields.valid_address}</p>
</div>
<div>
<label>username:</label>
<input type="text" noValidate name="uname" onChange={this.changeHandler}/>
</div>
<div>
<label>password:</label>
<input type="password" noValidate name="pass" onChange={this.changeHandler}/>
</div>
<div>
<label>address:</label>
<textarea noValidate name="address" onChange={this.changeHandler}></textarea>
</div>
<div>
<button onClick={this.submitForm}></button>
</div>
<div>{this.state.delete_data.length}
{this.state.delete_data.map((a,i)=>{
return <ul key={i}> <li>{i}</li><li>{a.username}</li>
<li>{a.password}</li>
<li>{a.address}</li>
<li><a href="#" onClick={()=>{this.deleteClick(this,a)}}>Delete</a></li>
<li><a href="#" onClick={()=>{this.editClick(this,a)}}>Edit</a></li></ul>
})}
</div>
{ this.state.edit_showui==true &&
<div>
<div>
<label>username:</label>
<input type="text" noValidate name="uname_edit" value={this.state.edit_obj.username} onChange={e => this.editchangeHandler(e)} />
</div>
<div>
<label>password:</label>
<input type="password" noValidate name="pass_edit" value={this.state.edit_obj.password} onChange={this.editchangeHandler.bind(this)} />
</div>
<div>
<label>address:</label>
<textarea noValidate name="address_edit" value={this.state.edit_obj.address} onChange={this.editchangeHandler.bind(this)}></textarea>
</div>
<div>
<button onClick={this.updateval.bind(this)}>update</button>
</div>
<div>{this.state.edit_obj.username}</div>
<div>{this.state.edit_obj.password}</div>
<div>{this.state.edit_obj.address}</div>
</div>
}
editdata:
<div>{this.state.edit_data.username}</div>
<div>{this.state.edit_data.password}</div>
<div>{this.state.edit_data.address}</div>
{this.state.edit_data.map((q,i)=>{
return <ul key={i}> <li>{i}</li><li>{q.username}</li>
<li>{q.password}</li>
<li>{q.address}</li>
</ul>
})}
}
</div>
)//return ends
}
}
export default Form;
thanks in advance.

Related

How do I put a form validation here so that the user must enter a name, email, and a contact number before submitting?

I'd like to make a validation so that the user would input a valid name, email and contact number before being accepted as a submission.
import React, { Component } from 'react'
import ContactService from '../services/ContactService';
class CreateContacts extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
name: '',
email: '',
contact: '',
}
this.changeNameHandler = this.changeNameHandler.bind(this);
this.saveOrUpdateContact = this.saveOrUpdateContact.bind(this);
this.changeContactHandler = this.changeContactHandler.bind(this);
}
componentDidMount(){
if(this.state.id === '_add'){
return
}else{
ContactService.getContactById(this.state.id).then( (res) =>{
let contact = res.data;
this.setState({name: contact.name,
email: contact.email,
contactMain: contact.contact,
});
});
}
}
saveOrUpdateContact = (e) => {
e.preventDefault();
let contact = {name: this.state.name, email: this.state.email, contact: this.state.contact};
console.log('contact => ' + JSON.stringify(contact));
if(this.state.id === '_add'){
ContactService.createContact(contact).then(res =>{
this.props.history.push('/users');
});
}else{
ContactService.updateContact(contact, this.state.id).then( res => {
this.props.history.push('/users');
});
}
}
changeNameHandler= (event) => {
this.setState({name: event.target.value});
}
changeEmailHandler= (event) => {
this.setState({email: event.target.value});
}
changeContactHandler= (event) => {
this.setState({contact: event.target.value});
}
cancel(){
this.props.history.push('/users');
}
getTitle(){
if(this.state.id === '_add'){
return <h3 className="text-center">Add Contact</h3>
}else{
return <h3 className="text-center">Update Contact</h3>
}
}
render() {
return (
<div>
<br></br>
<div className = "container">
<div className = "row">
<div className = "card col-md-6 offset-md-3 offset-md-3">
{
this.getTitle()
}
<div className = "card-body">
<form>
<div className = "form-group">
<label> Name: </label>
<input placeholder="Name" name="name" className="form-control"
value={this.state.name} onChange={this.changeNameHandler}/>
</div>
<div className = "form-group">
<label> Email: </label>
<input placeholder="Email" name="email" className="form-control"
value={this.state.email} onChange={this.changeEmailHandler}/>
</div>
<div className = "form-group">
<label> Contact: </label>
<input placeholder="Contact" name="contact" className="form-control"
value={this.state.contact} onChange={this.changeContactHandler}/>
</div>
<button className="btn btn-success" onClick={this.saveOrUpdateContact}>Save</button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default CreateContacts

ReactJs: Defaultvalue of textArea not updated

I'm working on a form in my ReactJs app. What I'd like to do:
1/ select a draft letter from an array of draft letters by its id // ok
2/ display the title, body and location of the selected draft letter in a form below // ok
3/ then the user should be able to edit all the fields // not ok!
This is what I did :
class NewLetter extends Component {
constructor(props) {
super(props)
this.state = {
city: "",
title: "",
letterBody: "",
}
this.handleChange_city = this.handleChange_city.bind(this);
this.handleChange_letterBody = this.handleChange_letterBody.bind(this);
this.handleChange_title = this.handleChange_title.bind(this);
}
handleChange_city(e) {
this.setState({
city: e.target.value
});
}
handleChange_letterBody(e) {
this.setState({
title: e.target.value
});
}
handleChange_title(e) {
this.setState({
letterBody: e.target.value
});
}
render() {
return (
<form className="containerLetter">
<div className="form-group">
<input type="text" className="form-control" id="letterLocation" placeholder="where are you?" value={this.props.city} onChange={this.handleChange_city}/>
</div>
<div className="form-group">
<input type="text" className="form-control" id="letterTitle" placeholder="give a title to your letter" value={this.props.title} onChange={this.handleChange_title} />
</div>
<div className="form-group">
<textarea type="text" className="form-control" id="letterBody" placeholder="Letter content" value={this.props.letterBody} onChange={this.handleChange_letterBody} />
</div>
<button className="actionButton">Send the letter</button> <br />
<button className="actionButton">Save as draft</button>
</form>
)
}
}
export default NewLetter
If I use value, the fields are not editable
If I use defaultValue the field are editable but when the defaultValue change, React doesn't re-render. The values are passed as props by the parent component:
class DraftLetters extends Component {
constructor(props) {
super(props)
this.state = {
selectedDraftIndex: 0,
};
this.handleChange = this.handleChange.bind(this);
}
getListOfDrafts = () => {
var list = []
for (let i = 0; i < this.props.drafts.length; i++) {
list.push(<option value={i}> {this.props.drafts[i].redactionDate} </option>);
}
return (list);
}
handleChange(e) {
this.setState({
selectedDraftIndex: e.target.value,
})
}
render() {
return (
<div >
{(this.props.drafts.length != 0) &&
<div className="form-group selectLetter">
<label for="sel1">Select the draft:</label>
<select onChange={this.handleChange} className="form-control" id="sel1">
{this.getListOfDrafts()}
</select>
</div>
}
{(this.props.drafts.length == 0) &&
<div className="form-group">
<p className="noLetter"> You haven't saved any draft.</p>
<img width="400px" className="img-fluid" src={painting} alt="tableau"></img>
</div>
}
<div>
<br />
{(this.props.drafts.length != 0) &&
<NewLetter city={this.props.drafts[this.state.selectedDraftIndex].city}
title={this.props.drafts[this.state.selectedDraftIndex].title}
letterBody={this.props.drafts[this.state.selectedDraftIndex].letterBody}></NewLetter>
}
{this.state.selectedDraftIndex}
</div>
</div>
)
}
}
export default DraftLetters
It seems to be a well known problem
This is what I found:
defaultValue change does not re-render input
React input defaultValue doesn't update with state
https://github.com/facebook/react/issues/4101
Is there nowdays a fix for this problem?

React.JS TypeError: Cannot read property 'value' of undefined

Having an issue with a react form and I can't figure it out. I am getting TypeError: Cannot read property 'value' of undefined when submitting. The issue started when I added "location" to the form. Not sure how this is causing it to break as I am just adding another item to the form. I have attempted to fix any typos, and when I take out the "location" it submits with no issue.
import React from "react";
import Firebase from "firebase";
import config from "./config";
class App extends React.Component {
constructor(props) {
super(props);
Firebase.initializeApp(config);
this.state = {
pallets: []
};
}
componentDidMount() {
this.getUserData();
}
componentDidUpdate(prevProps, prevState) {
if (prevState !== this.state) {
this.writeUserData();
}
}
writeUserData = () => {
Firebase.database()
.ref("/")
.set(this.state);
console.log("DATA SAVED");
};
getUserData = () => {
let ref = Firebase.database().ref("/");
ref.on("value", snapshot => {
const state = snapshot.val();
this.setState(state);
});
};
handleSubmit = event => {
event.preventDefault();
let name = this.refs.name.value;
let QTY = this.refs.QTY.value;
let uid = this.refs.uid.value;
let location = this.refs.location.value;
if (uid && name && QTY && location) {
const { pallets } = this.state;
const devIndex = pallets.findIndex(data => {
return data.uid === uid;
});
pallets[devIndex].name = name;
pallets[devIndex].QTY = QTY;
pallets[devIndex].location = location;
this.setState({ pallets });
} else if (name && QTY && location) {
const uid = new Date().getTime().toString();
const { pallets } = this.state;
pallets.push({ uid, name, QTY, location });
this.setState({ pallets });
}
this.refs.name.value = "";
this.refs.QTY.value = "";
this.refs.uid.value = "";
this.refs.location.value = "";
};
removeData = pallet => {
const { pallets } = this.state;
const newState = pallets.filter(data => {
return data.uid !== pallet.uid;
});
this.setState({ pallets: newState });
};
updateData = pallet => {
this.refs.uid.value = pallet.uid;
this.refs.name.value = pallet.name;
this.refs.QTY.value = pallet.QTY;
this.refs.location.value =pallet.location;
};
render() {
const { pallets } = this.state;
return (
<React.Fragment>
<div className="container">
<div className="row">
<div className="col-xl-12">
<h1>Creating Pallet App</h1>
</div>
</div>
<div className="row">
<div className="col-xl-12">
{pallets.map(pallet => (
<div
key={pallet.uid}
className="card float-left"
style={{ width: "18rem", marginRight: "1rem" }}
>
<div className="card-body">
<h5 className="card-title">{pallet.name}</h5>
<p className="card-text">{pallet.QTY}</p>
<p className="card-text">{pallet.location}</p>
<button
onClick={() => this.removeData(pallet)}
className="btn btn-link"
>
Delete
</button>
<button
onClick={() => this.updateData(pallet)}
className="btn btn-link"
>
Edit
</button>
</div>
</div>
))}
</div>
</div>
<div className="row">
<div className="col-xl-12">
<h1>Add new pallet here</h1>
<form onSubmit={this.handleSubmit}>
<div className="form-row">
<input type="hidden" ref="uid" />
<div className="form-group col-md-6">
<label>Name</label>
<input
type="text"
ref="name"
className="form-control"
placeholder="Name"
/>
</div>
<div className="form-group col-md-6">
<label>QTY</label>
<input
type="text"
ref="QTY"
className="form-control"
placeholder="QTY"
/>
</div>
<div className="form-group col-md-6">
<label>Location</label>
<input
type="text"
ref="QTY"
className="form-control"
placeholder="Location"
/>
</div>
</div>
<button type="submit" className="btn btn-primary">
Save
</button>
</form>
</div>
</div>
</div>
</React.Fragment>
);
}
}
export default App;
You haven't created a ref named location
Change:
<input
type="text"
ref="QTY"
className="form-control"
placeholder="Location"
/>
to:
<input
type="text"
ref="location"
className="form-control"
placeholder="Location"
/>

how to check if string contains number with react

I am building a user validation website, I want each input to verify if the string that was entered:
Have uppercase first letter
doesn't contain numbers
doesn't contain "$%^&*()"
I did the first task, but I can't do the last ones.
I have tried !isNaN(firstName) === true and it wont work
import React, { Component } from 'react';
class Profile extends Component {
state = {
details: {
firstName: '',
lastName: '',
ID: '',
Email: ''
},
error: false,
complete: false
};
OnSubmit = e => {
e.preventDefault();
const { firstName } = this.state.details;
if (
firstName.charAt(0) !== firstName.charAt(0).toUpperCase() &&
!isNaN(firstName) === true
) {
this.setState({ error: true });
} else {
this.setState({ complete: true });
}
};
OnChange = e => {
e.preventDefault();
this.setState({
details: { ...this.state.details, [e.target.name]: e.target.value }
});
};
render() {
return (
<div>
<div className="container text-center mt-4" style={{ width: '500px' }}>
<form className="px-4 py-3" onSubmit={this.OnSubmit}>
<div className="form-group">
{this.state.error === true ? (
<p className="text-danger">
Some of the details are wrong check the fields above
</p>
) : null}
<label>First Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="firstName"
/>
</div>
<div className="form-group">
<label>Last Name:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="lastName"
/>
</div>
<div className="form-group">
<label>ID Number:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="ID"
/>
</div>
<div className="form-group">
<label>Email:</label>
<input
type="text"
className="form-control"
onChange={this.OnChange}
name="Email"
/>
</div>
<button type="submit" className="btn btn-secondary mt-3">
Check
</button>
</form>
</div>
</div>
);
}
}
export default Profile;
function validateName(name) {
var isValidName = true;
if(/[!##$%^&*(),.?":{}|<>]/g.test(name) || !/^[A-Z]/.test(name) || /\d+/g.test(name)) {
isValidName = false;
}
return isValidName;
}
validateName("David")
You can use regex.
!firstName.match(/\d/)
\d checks for the numbers
First split firstName, then check for Number in that array
OnSubmit = e => {
e.preventDefault();
const { firstName } = this.state.details;
let firstNameArr = firstName.split('');
for(value of firstName.split('')){
if (!isNaN(value) {
this.setState({ error: true });
} else {
this.setState({ complete: true });
}
}
};
This is how I would do it:
const test1 = "%2mfas1k";
const test2 = '123';
const test3 = 'test';
function test(str) {
const match = str.match(/\d+/g);
const isArray = Array.isArray(match);
if(isArray) return match.map(Number);
return false
}
// If test return a result not falsy, contains a number
console.log(test(test1)); // [2, 1]
console.log(test(test2)); // [123]
console.log(test(test3)); // false
Here is a working example, i have split each part into its own checker to make it easier to understand.
let string = "Asdfsdf$32";
let special_characters = ['$','%','^','&','*','(',')'];
let string_array = string.split('');
// Upper case check
if(string[0] === string[0].toUpperCase()) {
console.log("First letter is uppercase")
} else {
console.log("First letter is not uppercase")
}
// No numbers check
if(string.match(/\d/)) {
console.log("Digit Found")
} else {
console.log("No Digit Found")
}
// Special Characters
if(string_array.find(item => special_characters.includes(item))) {
console.log("Special Character Found")
} else {
console.log("No Special Character Found")
}
export function checkDigit(username){
if(username.match(/\d/)) {
console.log("Digit Found")
return true;
}else {
return false;
}
}
let username = this.state.name;
if(checkDigit(username)){
showInfoAlert(NAME_VALIDATION_DIGIT)
return
}

Grabbing React form field values for submission

Given a React form, I'm having trouble getting the value from the selected radio button, and text box if other is selected. I should be able to pass the fields into the send() for the post, but not sure how to grab them.
class CancelSurvey extends React.Component {
constructor (props) {
super(props)
this.state = {
reasons: [],
reason: {}
}
this.processData = this.processData.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.otherSelected = this.state.reason === "otheroption";
}
componentDidMount () {
this.fetchContent(this.processData)
}
/**
* Fetch reasons
*/
fetchContent (cb) {
superagent
.get('/api/user/survey')
.then(cb)
}
/**
* Set state after reasons have been fetched
* #param data
*/
processData (data) {
this.setState({
reasons: data.body
})
}
handleSubmit (e) {
e.preventDefault()
let reason = this.state.reason
if (reason === 'otheroption') {
reason = this.state.otherreason
}
console.log(reason)
superagent
.post('/api/user/survey')
.send({
optionId: this.state.reason.reason_id,
optionText: this.state.reason.client_reason,
otherReasonText: this.state.otherreason
})
.then(function (res) {
console.log('Survey Sent!')
})
}
/**
* render
*/
render (props) {
const content = this.props.config.contentStrings
const reason = this.state.reasons.map((reason, i) => {
return (
<div className='fieldset__item' key={i}>
<label>{reason.client_reason}</label>
<input type='radio'
id={reason.reason_id}
value={reason.client_reason}
name='reason'
checked={this.state.reason.reason_id === reason.reason_id}
onChange={() => this.setState({reason})} />
</div>
)
})
return (
<div className='survey'>
<h2 className='heading md'>{content.memberCancel.exitSurvey.heading}</h2>
<p className='subpara'>{content.memberCancel.exitSurvey.subHeading}</p>
<form id='exit-survey' onSubmit={this.handleSubmit}>
<fieldset className='fieldset'>
{ reason }
<label>Other reason not included above:</label>
<input type='radio'
id='otheroption'
name='reason'
value={this.state.reason.otherreason}
onChange={() => this.setState({reason:{reason_id: 70, client_reason: 'other'}})} />
<input className='valid'
type='text'
id='otheroption'
name='othertext'
placeholder={content.memberCancel.exitSurvey.reasonPlaceholder}
onChange={(event) => this.setState({otherreason: event.target.value})} />
</fieldset>
<div className='footer-links'>
<button className='btn btn--primary btn--lg' onClick={this.handleSubmit}>{content.memberCancel.exitSurvey.button}</button>
</div>
</form>
</div>
)
}
}
export default CancelSurvey
Your variables aren't correct. I've update them to what I think is correct.
handleSubmit (e) {
e.preventDefault()
superagent
.post('/api/user/survey')
.send({
optionId: this.state.reason.reason_id,
optionText: this.state.reason.client_reason,
otherReasonText: this.state.reason.otherreason
})
.then(function (res) {
console.log('Survey Sent!')
})
.catch(function (err) {
console.log('Survey submission went wrong...')
})
}
/**
* render
*/
render (props) {
const content = this.props.config.contentStrings
const reason = this.state.reasons.map((reason, i) => {
return (
<div className='fieldset__item' key={i}>
<label>{reason.client_reason}</label>
<input
type='radio'
id={reason.reason_id}
name='reason'
checked={this.state.reason.reason_id === reason.reason_id}
value={reason.client_reason}
onChange={() => this.setState({reason})} />
</div>
)
})
return (
<div className='survey'>
<h2 className='heading md'>{content.memberCancel.exitSurvey.heading}</h2>
<p className='subpara'>{content.memberCancel.exitSurvey.subHeading}</p>
<form id='exit-survey' onSubmit={this.handleSubmit}>
<fieldset className='fieldset'>
{ reason }
<label>Other reason not included above:</label>
<input type='radio'
id='otheroption'
name='otheroption'
value={this.state.reason.otherreason}
checked={this.state.reason.reason_id === 0}
onChange={() => this.setState({ reason: {reason_id: 0, client_reason: ""} })} />
<input className='valid'
type='text'
id='othertext'
name='othertext'
value={this.state.reason.otherreason}
placeholder={content.memberCancel.exitSurvey.reasonPlaceholder}
onChange={(event) => this.setState({ reason: {reason_id: 0, client_reason: "", otherreason: event.target.value} })} />
</fieldset>
<div className='footer-links'>
<button className='btn btn--primary btn--lg' onClick={this.handleSubmit}>{content.memberCancel.exitSurvey.button}</button>
</div>
</form>
</div>
);
}

Resources