Cannot modify value nor placeholder of HTML forms - html

I'm building this app with react, when pass the actual value like
<div class="form-group">
<input
value={this.state.setupList[0]} onChange{this.handleChange}
name="date" class="form-control" placeholder={this.state.setupList[0]} />
</div>
I can see the text but no modifications allowed, that's the function I'm using for the form:
handleChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
Please someone suggest a better approach to fix the issue
Structure of the constructor
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
setupList: [],
title: '',
description: '',
show: false,
};
}
A random function I found on internet to store input in a value
handleChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
With that I update the db
updateData = e => {
this.setState({ loading: true})
const { currentUser } = fire.auth();
e.preventDefault();
let title = this.state.title;
let description = this.state.description;
fire.database().ref(`/master/${currentUser.uid}/setup/`)
.update({
title: this.state.title,
description: this.state.description,
})
.then(() => {
this.setState({ loading: false, show:false})
});
}
And probably the issue is here
componentDidMount = () => {
fire.database().ref(`/master/${currentUser.uid}/setup/`)
.on('value', snapshot => {
var obj = snapshot.val()
var setupList = []
var keys = []
for(let a in obj){
setupList.push(obj[a])
keys.push(a)
}
this.setState({
setupList:setupList,
keys:keys,
...

Changing value to defaultValue works as expected. Such an easy solution
<div class="form-group">
<input
defaultValue={this.state.setupList[0]} onChange{this.handleChange}
name="date" class="form-control" placeholder={this.state.setupList[0]} />
</div>

Related

How to send formdata with other data in MERN App?

I want to save a image to cloudiary from Nodejs in a Mern Application. I have data in such a way that formdata is a field.
I want to send multiple fields from frontend with formdata but whenever I am trying to assign the formdata to my object, it is getting assigned as empty object {}
Code for Component where I have 2 more fields apart from formdata or file input.
import axios from "axios";
import React, { useState } from "react";
function About({ setAboutInfo, touched = false, setInvalid }) {
const [about, setAbout] = useState({
name: "",
objective: "",
imageUrl: {},
});
const handleChange = (e) => {
var formData = new FormData();
if (e.target.name == "imageUrl") {
formData.append("imageUrl", e.target.files[0]);
setAbout({ ...about, imageUrl: formData });
} else setAbout({ ...about, [e.target.name]: e.target.value });
setAboutInfo(about);
if (!(about.name && about.objective)) {
setInvalid((prev) => ({ ...prev, about: true }));
} else {
setInvalid((prev) => ({ ...prev, about: false }));
}
};
return (
<div className="ext-container row pb-0">
<form encType="multipart/form-data">
<div className="col-md-6">
<label className="my-labels" htmlFor="">
Name
</label>
<input
value={about.name}
name="name"
type="text"
onChange={handleChange}
className={"my-inputs "}
placeholder="Enter complete name"
/>
</div>
<div className="col-md-6">
<label className="my-labels" htmlFor="">
Profile Pic
</label>
> <input
> name="imageUrl"
> type="file"
> accept="image/*"
> onChange={handleChange}
> className={"my-inputs "}
> placeholder="Choose profile pic"
> />
</div>
<div className="col-md-12">
<label className="my-labels" htmlFor="">
Objective
</label>
<textarea
name="objective"
value={about.objective}
type="text"
onChange={handleChange}
className={"my-inputs "}
rows={4}
placeholder="Enter Objective"
></textarea>
</div>
</form>
</div>
);
}
export default About;
I am sending this data to parent component from setAboutInfo method.
Parent component making request to backend
const saveData = (e) => {
e.preventDefault();
setTouched(true);
console.log({
...about,
});
// console output
**
{
name: 'Jack', objective: "Jack's objective", imageUrl: FormData}
imageUrl: FormData {}
name: "Jack"
objective: "Jack's objective"
[[Prototype]]: Object
}
**
axios
.post(
"/resume",{...about})
.then((response) => {
if (response.status == 201) {
console.log(response);
success("Data saved successfully");
}
})
.catch((e) => console.log(e));
};
In backend I am getting this as body of Post request
{ name: 'Jack', objective: "Jack's objective", imageUrl: {} }
You have to append whole body in formdata and send send form data to the api.
const saveData = (e) => {
e.preventDefault();
setTouched(true);
console.log({
...about,
});
// console output
**
{
name: 'Jack', objective: "Jack's objective", imageUrl: FormData}
imageUrl: FormData {}
name: "Jack"
objective: "Jack's objective"
[[Prototype]]: Object
}
**
let formData = new FormData();
formData.append("imageUrl", about.imageUrl);
formData.append("name", about.name);
formData.append("objective", about.objective);
axios
.post(
"/resume",formData )
.then((response) => {
if (response.status == 201) {
console.log(response);
success("Data saved successfully");
}
})
.catch((e) => console.log(e));
};
For onchange method don't save in form data.
const handleChange = (e) => {
if (e.target.name == "imageUrl") {
setAbout({ ...about, imageUrl: e.target.files[0]});
} else setAbout({ ...about, [e.target.name]: e.target.value });
setAboutInfo(about);
if (!(about.name && about.objective)) {
setInvalid((prev) => ({ ...prev, about: true }));
} else {
setInvalid((prev) => ({ ...prev, about: false }));
}
};

how to set url in another input after upload file in reactjs

I am working with react with axios. i am uploading a file in react and i want to set url in another input after file upload but i am unable to get value. in console i am getting value properly but issue in input field. currently i m doing with different method.
i want uploaded file url in id="uploadRhp". please help if anybody know.
import React, { Component } from 'react';
import axios from "axios";
class TradeImportComponent extends React.Component<{},any>{
// API Endpoints
custom_file_upload_url = `https://exaample.com/api/ipo/document/upload`;
canvas: any;
// state
constructor(props) {
super(props);
this.canvas = React.createRef()
this.state = {
image_file: null,
image_preview: '',
}
}
// Image Preview Handler
handleImagePreview = (e) => {
let image_as_base64 = URL.createObjectURL(e.target.files[0])
let image_as_files = e.target.files[0];
this.setState({
image_preview: image_as_base64,
image_file: image_as_files,
})
}
// Image/File Submit Handler
handleSubmitFile = () => {
if (this.state.image_file !== null){
let formData = new FormData();
formData.append('ipoName', 'tata');
formData.append('document', this.state.image_file);
axios.post(
this.custom_file_upload_url,
formData,
{
headers: {
// "Authorization": "YOUR_API_AUTHORIZATION_KEY_SHOULD_GOES_HERE_IF_HAVE",
"Content-type": "multipart/form-data",
},
}
)
.then(res => {
console.log(`Success` + res.data.response);
var json= JSON.parse(JSON.stringify(res.data.response));
console.log(json);
console.log(json.url);
console.log(this.canvas.current.value);
this.canvas.current.value=json.url;
console.log(this.canvas.current.value);
})
.catch(err => {
console.log(err);
})
}
}
// render from here
render() {
return (
<div>
{/* image preview */}
<img src={this.state.image_preview} alt="image_preview" width="100%"/>
{this.state.url}
{/* image input field */}
<input
type="file"
onChange={this.handleImagePreview}
/>
<input type="hidden" name="logo" id="uploadlogo"/>
<input type="hidden" name="rhp" value="test#1234567" ref={this.canvas} id="uploadRhp"/>
<input type="hidden" name="financial_Pdf" id="uploadfinancial"/>
<label>Upload file</label>
<input type="submit" onClick={this.handleSubmitFile} value="Submit"/>
<ul>
</ul>
</div>
);
}
}
export default TradeImportComponent;
Use setstate in axios response store the response in state
// state
constructor(props) {
super(props);
this.canvas = React.createRef()
this.state = {
image_file: null,
image_preview: '',
uploadURL:''
}
}
handleSubmitFile = () => {
if (this.state.image_file !== null){
let formData = new FormData();
formData.append('ipoName', 'tata');
formData.append('document', this.state.image_file);
return axios.post(
this.custom_file_upload_url,
formData,
{
headers: {
// "Authorization": "YOUR_API_AUTHORIZATION_KEY_SHOULD_GOES_HERE_IF_HAVE",
"Content-type": "multipart/form-data",
},
}
)
.then(res => {
console.log(`Success` + res.data.response);
var json= JSON.parse(JSON.stringify(res.data.response));
//use setstate
setState({uploadURL:json.url)
})
.catch(err => {
console.log(err);
})
}
}
//in JSX render
<Input value={this.state.uploadUrl}/>

Set multiple search filter in ReactJS

I need help because i'm stuck in my reactjs project. I'm trying to make multiple search input box with different filter each in reactJS, but i can't achieve it with more than one filter. I tried googling it but i cannot make it work.
searchFilter = () => {
return <form>
<input name="filterTitle" type="text" value={this.state.filterTitle} onChange={this.filterList}/>
<input name="filterYear" type="text" value={this.state.filterYear} onChange={this.filterList}/>
<input name="filterReso" type="text" value={this.state.filterReso} onChange={this.filterList}/>
</form>
}
filterList = (event) => {
var items = this.state;
var updatedItems = this.state.items.filter(item => {
var filterTitle = this.state.filterTitle != "" ? item.titulo.toLowerCase().indexOf(event.target.value.toLowerCase()) !== -1 : true;
var filterYear = this.state.filterYear != "" ? item.ano.toLowerCase().indexOf(event.target.value.toLowerCase()) !== -1 : true;
var filterReso = this.state.filterReso != "" ? item.reso.toLowerCase().indexOf(event.target.value.toLowerCase()) !== -1 : true;
return filterTitle && filterYear && filterReso;
})
this.setState({ updatedItems: updatedItems });
console.log(updatedItems);
}
UPDATE 1:
new code so far, please help!
handleSearchFilter = (event) => {
const inputValue = event.target.value;
this.setState({ input: inputValue });
this.filterList(inputValue);
};
searchFilter = () => {
return <form>
<input name="filterTitle" type="text" value={this.filterTitle} onChange={(e)=>this.handleSearchFilter(e)} />
<input name="filterYear" type="text" value={this.filterYear} onChange={(e)=>this.handleSearchFilter(e)} />
<input name="filterReso" type="text" value={this.filterReso} onChange={(e)=>this.handleSearchFilter(e)} />
</form>
}
filterList = (inputValue) => {
const {items, updatedItems} = this.state;
const itemsUpdate = this.state.items.filter(item => {
var filterTitle = item.titulo.toLowerCase().indexOf(inputValue.toLowerCase()) > 1;
var filterYear = item.ano.toLowerCase().indexOf(inputValue.toLowerCase()) > 1;
var filterReso = item.reso.toLowerCase().indexOf(inputValue.toLowerCase()) > 1;
return filterTitle + filterYear + filterReso;
})
this.setState({ updatedItems: itemsUpdate });
console.log(updatedItems);
}
first you need to save search key seperate in state then make AND or OR comparison to retrive result like this
import React from "react";
class TestPage extends React.Component {
state = {
items: [
{
titulo: "titulo1",
ano: "ano1",
reso: "reso1",
},
{
titulo: "titulo2",
ano: "ano2",
reso: "reso2",
},
],
updatedItems: [],
filterTitle: "",
filterYear: "",
filterReso: "",
};
searchFilter = () => {
return (
<form>
<input
name="filterTitle"
type="text"
value={this.filterTitle}
onChange={(e) => this.handleSearchFilter(e, "filterTitle")}
/>
<input
name="filterYear"
type="text"
value={this.filterYear}
onChange={(e) => this.handleSearchFilter(e, "filterYear")}
/>
<input
name="filterReso"
type="text"
value={this.filterReso}
onChange={(e) => this.handleSearchFilter(e, "filterReso")}
/>
</form>
);
};
handleSearchFilter = (event, key) => {
const inputValue = event.target.value;
this.setState({ [key]: inputValue }, () => {
this.filterList();
});
};
filterList = () => {
const itemsUpdate = this.state.items.filter((item) => {
var filterTitle =
item.titulo
.toLowerCase()
.indexOf(this.state.filterTitle.toLowerCase()) > -1;
var filterYear =
item.ano.toLowerCase().indexOf(this.state.filterYear.toLowerCase()) >
-1;
var filterReso =
item.reso.toLowerCase().indexOf(this.state.filterReso.toLowerCase()) >
-1;
return filterTitle && filterYear && filterReso;
});
this.setState({ updatedItems: itemsUpdate }, () => {
console.log(this.state.updatedItems);
});
};
renderList = () => {
const { updatedItems } = this.state;
return (
<div>
{updatedItems.map((updatedItem) => {
return (
<div>
{updatedItem.titulo}
{updatedItem.ano}
{updatedItem.reso}
</div>
);
})}
</div>
);
};
render() {
return (
<div>
{this.searchFilter()}
{this.renderList()}
</div>
);
}
}
export default TestPage;
First of all you need to store the input values corresponding to each input in state and post that you need to filter the items array.
I assume you wish to do an AND operation on filters. IF you wish to do an OR operation just change it in the code below
handleSearchFilter = (event) => {
const {value, name} = event.target;
this.setState({ [name]: value }, () => {
this.filterList();
}); // use setState callback to now filter the list
};
searchFilter = () => {
return <form>
<input name="filterTitle" type="text" value={this.state.filterTitle} onChange={this.handleSearchFilter} />
<input name="filterYear" type="text" value={this.state.filterYear} onChange={(e)=>this.handleSearchFilter} />
<input name="filterReso" type="text" value={this.state.filterReso} onChange={this.handleSearchFilter} />
</form>
}
filterList = () => {
const {items, updatedItems, filterTitle, filterYear, filterReso} = this.state;
const itemsUpdate = this.state.items.filter(item => {
var filterTitleRes = item.titulo.toLowerCase().indexOf(filterTitle.toLowerCase()) > 1;
var filterYearRes = item.ano.toLowerCase().indexOf(filterYear.toLowerCase()) > 1;
var filterResoRes = item.reso.toLowerCase().indexOf(filterReso.toLowerCase()) > 1;
return filterTitleRes && filterYearRes && filterResoRes;
// Change the above condition to or if you wish to do an OR check
})
this.setState({ updatedItems: itemsUpdate });
console.log(itemsUpdate);
}
You can use js-search for optimized searching across multiple keys in JSON object.
In your case, you can simply create a smaller JSON array where you only store keys in which you want to search for example
import * as JsSearch from 'js-search';
var theGreatGatsby = {
isbn: '9781597226769',
title: 'The Great Gatsby',
author: {
name: 'F. Scott Fitzgerald'
},
tags: ['book', 'inspirational']
};
var theDaVinciCode = {
isbn: '0307474275',
title: 'The DaVinci Code',
author: {
name: 'Dan Brown'
},
tags: ['book', 'mystery']
};
var angelsAndDemons = {
isbn: '074349346X',
title: 'Angels & Demons',
author: {
name: 'Dan Brown',
},
tags: ['book', 'mystery']
};
var search = new JsSearch.Search('isbn');
search.addIndex('title');
search.addIndex(['author', 'name']);
search.addIndex('tags')
search.addDocuments([theGreatGatsby, theDaVinciCode, angelsAndDemons]);
search.search('The'); // [theGreatGatsby, theDaVinciCode]

React Ant Design editable table

so I follow up this documentation for creating a editable row; It's a CSS library for React from Ant Design, I am stuck at the following:
How do I pass the changed row, the newData[index] to an onChange event?
How do I update a set of row of data to a back-end rest api? I managed to create data using form from Ant Design, but I don't know how to update it using editable row
Fyi, the back end works perfectly with postman: create, update, delete
How do I get the id of this code?
axios.put("/api/product/update/:id"
I tried to replace the id with ${id}, ${index}, ${products[index]} (with template literal) but it doesn't work.
Here are the full code:
import React from 'react';
import axios from 'axios';
import { Table, Input, InputNumber, Popconfirm, Form } from 'antd';
const FormItem = Form.Item;
const EditableContext = React.createContext();
const EditableRow = ({ form, index, ...props }) => (
<EditableContext.Provider value={form}>
<tr {...props} />
</EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);
class EditableCell extends React.Component {
getInput = () => {
if (this.props.inputType === 'number') {
return <InputNumber />;
}
return <Input />;
};
render() {
const {
editing,
dataIndex,
title,
inputType,
record,
index,
...restProps
} = this.props;
return (
<EditableContext.Consumer>
{(form) => {
const { getFieldDecorator } = form;
return (
<td {...restProps}>
{editing ? (
<FormItem style={{ margin: 0 }}>
{getFieldDecorator(dataIndex, {
rules: [{
required: true,
message: `Please Input ${title}!`,
}],
initialValue: record[dataIndex],
})(this.getInput())}
</FormItem>
) : restProps.children}
</td>
);
}}
</EditableContext.Consumer>
);
}
}
class EditableTable extends React.Component {
constructor(props) {
super(props);
this.state = { products: [], editingKey: '' };
this.columns = [
{
title: 'Product Name',
dataIndex: 'productname',
width: '25%',
editable: true,
},
{
title: 'OS',
dataIndex: 'os',
width: '10%',
editable: true,
},
{
title: 'Category',
dataIndex: 'category',
width: '15%',
editable: true,
},
{
title: 'Model',
dataIndex: 'model',
width: '20%',
editable: true,
},
{
title: 'Serial Number',
dataIndex: 'serialnumber',
width: '20%',
editable: true,
},
{
title: 'Operation',
dataIndex: 'operation',
width: '10%',
render: (text, record) => {
const editable = this.isEditing(record);
return (
<div>
{editable ? (
<span>
<EditableContext.Consumer>
{form => (
<a
href="javascript:;"
onClick={() => this.save(form, record.id)}
style={{ marginRight: 8 }}
>
Save
</a>
)}
</EditableContext.Consumer>
<Popconfirm
title="Sure to cancel?"
onConfirm={() => this.cancel(record.id)}
>
<a>Cancel</a>
</Popconfirm>
</span>
) : (
<a onClick={() => this.edit(record.id)}>Edit</a>
)}
</div>
);
},
},
];
}
handleCategoryChange = event => { this.setState({ category: event.target.value }) }
handleProductNameChange = event => { this.setState({ productname: event.target.value }) }
handleOsNameChange = event => { this.setState({ os: event.target.value }) }
handleModelchange = event => { this.setState({ model: event.target.value }) }
handleSerialnumberChange = event => { this.setState({ serialnumber: event.target.value }) }
handlePriceChange = event => { this.setState({ price: event.target.value }) }
handleEquipmentChange = event => { this.setState({ equipment_condition: event.target.value }) }
handleDetailChange = event => { this.setState({ detail: event.target.value }) }
handleImageChange = event => { this.setState({ image: event.target.value }) }
handleSubmit = event => {
event.preventDefault();
axios.put(`/api/product/update/:id`,
{
category: this.state.category,
productname: this.state.productname,
os: this.state.os,
serialnumber: this.state.serialnumber,
model: this.state.model,
price: this.state.price,
equipment_condition: this.state.equipment_condition,
detail: this.state.detail,
image: this.state.image
})
}
componentDidMount() {
axios.get('/api/product').then(res => {
this.setState({ products: res.data });
});
}
isEditing = (record) => {
return record.id === this.state.editingKey;
};
edit(id) {
console.log('products', this.state.products.id);
// console.log('recordid', record.id);
this.setState({ editingKey: id });
}
save(form, id) {
console.log('key', id)
form.validateFields((error, row) => {
if (error) {
return;
}
const newData = [...this.state.products];
const index = newData.findIndex(item => id === item.id);
if (index > -1) {
const item = newData[index];
newData.splice(index, 1, { ...item, ...row, });
this.setState({ products: newData, editingKey: '' });
console.log('newData', newData[index]) // data I want to update to API
console.log('category', newData[index].category) // category
} else {
newData.push(this.state.products);
this.setState({ products: newData, editingKey: '' });
}
});
}
cancel = () => {
this.setState({ editingKey: '' });
};
render() {
const components = {
body: {
row: EditableFormRow,
cell: EditableCell,
},
};
const columns = this.columns.map((col) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: record => ({
record,
inputType: col.dataIndex === 'serialnumber' ? 'number' : 'text',
dataIndex: col.dataIndex,
title: col.title,
editing: this.isEditing(record),
}),
};
});
return (
<Table
rowKey={this.state.id}
components={components}
bordered
dataSource={this.state.products}
columns={columns}
rowClassName="editable-row"
/>
);
}
}
export default EditableTable;
Update:
So I try put axios inside the save method, like so:
save(form, id) {
form.validateFields((error, row) => {
if (error) {
return;
}
const newData = [...this.state.products];
const index = newData.findIndex(item => id === item.id);
if (index > -1) {
const item = newData[index];
newData.splice(index, 1, { ...item, ...row, });
this.setState({ products: newData, editingKey: '' });
console.log('newData', newData[index]) // data I want to update to API
console.log('index', index) // index adalah index array
console.log('id', id) // id adalah nomor index dalam tabel database, jangan sampai tertukar
console.log('category', newData[index].category)
console.log('productname', newData[index].productname)
console.log('os', newData[index].os)
console.log('serialnumber', newData[index].serialnumber)
console.log('model', newData[index].model)
console.log('detail', newData[index].detail)
axios.put(`/api/product/update/:${id}`,
{
category: newData[index].category,
productname: newData[index].productname,
os: newData[index].os,
serialnumber: newData[index].serialnumber,
model: newData[index].model,
price: newData[index].price,
equipment_condition: newData[index].equipment_condition,
detail: newData[index].detail,
image: newData[index].image
})
} else {
newData.push(this.state.products);
this.setState({ products: newData, editingKey: '' });
}
});
It doesn't update the data on the database.
Someone might still need this, The antd table api.
You can pass the render key in your column with one to three parameters depending on what you need
function(text, record, index) {}
The column will look like this:
const column = [{
dataIndex: "firstName",
render: (text, record, index) => console.log(text, record, index)
}]
So there's this weird syntax that I have to remove from the url api.
Pay attention to the very minor details of the url; I noticed it from the console log from the back end / node:
axios.put(`/api/product/update/${id}`,
{
category: newData[index].category,
productname: newData[index].productname,
os: newData[index].os,
serialnumber: newData[index].serialnumber,
model: newData[index].model,
price: newData[index].price,
equipment_condition: newData[index].equipment_condition,
detail: newData[index].detail,
image: newData[index].image
})

ReactJS, Making POST Request

I tried to create POST request in ReactJS however it does not work I keep getting
POST http://localhost:3000/ 404 (Not Found)
error,
Can someone help me please what I am doing wrong I have been trying to do it for more than 4 hours now and it is getting annoying :/
Here is my app.jsx File
import React from 'react';
import ReactDOM from 'react-dom';
import "./main.css";
import $ from 'jquery';
class ContactForm extends React.Component{
componentDidMount(){
var $form = $('.send_JSON');
var $inputName = $('.get_name');
var $inputAge = $('.get_age');
var $inputPrefix = $('.get_prefix');
var $inputEmail = $('.get_email');
var url = 'http://localhost:3000/'; //Configurable endpoint
function loadJSON(){
$.ajax({
url: url,
dataType: 'json'
}).done(function(res){
console.log(res);
console.log("DONE!")
}).fail(function(error){
console.log(error);
console.log("NOT DONE!")
});
}
function sendForm(send_name, send_age, send_prefix, send_email){
$.ajax({
url: url,
method: 'post',
dataType: 'json',
data : {
name : send_name,
age : send_age,
prefix : send_prefix,
email : send_email
}
}).done(function(res){
loadJSON();
console.log(res);
}).fail(function(error){
console.log('Error while sending Form');
readyToSubmit : '0';
});
}
$form.on('submit', function(e){
e.preventDefault();
var name = $inputName.val();
var age = $inputAge.val();
var prefix = $inputPrefix.val();
var email = $inputEmail.val();
if(name !== '' && age > 0 && email !== ''){
sendForm(name, age, prefix, email);
$inputName.val('');
$inputAge.val(0);
$inputPrefix.val('');
$inputEmail.val('');
}
});
}
state = {
name: 'Name',
age: '',
prefix: '-',
email : 'E-mail address',
nameCheck: '',
ageCheck: '',
emailCheck: '',
readyToSubmit: ''
}
handleSubmit = (e)=>{
e.preventDefault()
sendForm();
this.setState({
nameCheck: this.state.name.length <= 0 && 'Name field has to be filled.',
ageCheck: this.state.age.length <= 0 && 'Age has to be more than 0',
emailCheck: this.state.email.search('#') <= 0 && 'Email field has to be filled and consist #',
readyToSubmit: this.state.name.length > 0 && this.state.age.length > 0 && this.state.email.search('#') > 0 ? `Success ${this.state.name}` : '',
})
}
handleChange = e =>{
this.setState({
name: e.target.value,
})
}
handleChange2 = e =>{
this.setState({
age: e.target.value
})
}
handleChange3 = e =>{
this.setState({
prefix: e.target.value
})
}
handleChange4 = e =>{
this.setState({
email: e.target.value
})
}
clearForm = () => {
document.getElementById("sendForm").reset();
this.setState({
name: "",
age: "",
prefix: "Mr",
email: " "
})
}
render(){
return(
<div>
<span className="tooltip">{this.state.readyToSubmit}</span>
<form onSubmit = {this.handleSubmit} id="sendForm" className="send_JSON">
<h2>Sii Application</h2>
<img src="../img/logo.png"/>
<p>Your Name</p>
<span className="tooltip">{this.state.nameCheck}</span>
<input onChange = {this.handleChange} value ={this.state.name} className="get_name"/>
<p>Your Age</p>
<span className="tooltip">{this.state.ageCheck}</span>
<input onChange = {this.handleChange2} value ={this.state.age} type="number" min="10" max="100" className="get_age"/>
<p>Your Prefix</p>
<select onChange = {this.handleChange3} value = {this.state.prefix} className="get_prefix">
<option value = 'Mr'>Mr</option>
<option value = 'Ms'>Ms</option>
<option value = 'Mrs'>Mrs</option>
</select>
<p>Your Email</p>
<span className="tooltip">{this.state.emailCheck}</span>
<input onChange = {this.handleChange4} value ={this.state.email} type="email" className="get_email"/>
<button type="reset" onClick = {this.clearForm} name="clear">Clear</button>
<button type="submit" name="send">Send</button>
</form>
</div>
)
}
}
class App extends React.Component {
render(){
return <ContactForm/>
}
}
document.addEventListener('DOMContentLoaded', function(){
ReactDOM.render(
<App/>,
document.getElementById('app')
);
});
I dont know if there is other way to do so, I tried Axio - which didnt work for me at all.
I suggest you looking at fetch() API instead of using jQuery Ajax to make HttpRequest. It is more lightweight and will make your code looks much simpler. Here is a link to the blog from Jake Archibald and was suggested by Google to learn how to use fetch():
https://jakearchibald.com/2015/thats-so-fetch/
Also, you can find some useful examples here from Google official documents:
https://developers.google.com/web/updates/2015/03/introduction-to-fetch
I hope it helps.
Adding to the fetch() API, you can also use axios for making HttpRequest.
It is promise based HTTP client for the browser and node.js.
Documentation is simple and available here.
Here is the example for GET request:
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// Want to use async/await? Add the `async` keyword to your outer
function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}