I have a button that removes a photo from an object that holds multiple photos:
<button class="btn" onClick={()=> this.removePhoto(index)}>remove</button>
For some reason after the removePhoto function runs it continues to the onsubmit function. The only thing I can think that could be causing this is the bindings but I am still a fairly new to react so I am not sure how to fix this.
export default class Edit extends Component {
constructor() {
super();
this.state = {
id: '',
title: '',
description: '',
photos: [],
categories: [],
selectedFile: '',
selectedFiles: '',
photo: '',
tags: [],
tagName: '',
};
this.removePhoto = this.removePhoto.bind(this);
}
onSubmit = (event) => {
event.preventDefault();
const photoCatUpdate = this.state.photos.map((obj, index) => {
obj.tag = this.state.tagName
return obj
});
const photos = JSON.stringify(photoCatUpdate)
let body = {
title: this.state.title,
description : this.state.description,
photos: photos,
tags: this.state.tagName
}
let id = this.state.id
fetch('/api/categories/' + id, {
method: 'put',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if (res.status === 200) {
console.log("WORKED!!")
this.props.closeModal()
this.props.getCategory()
} else {
const error = new Error(res.error);
throw error;
}
})
}
addPhoto = () => {
const photosNew = this.state.photos
const photo = this.state.photo
photosNew.push({
photo: photo,
title: '',
thumbnail: false,
image1: false,
image2: false,
tag: '',
});
this.setState({photos: photosNew});
this.setState({photo: '', selectedFile: '', selectedFiles: ''})
document.getElementById("myFile").value = "";
}
removePhoto = (i) => {
debugger
const photos = this.state.photos
const objIndex = photos.filter((obj, index) => {
if(index != i){
return obj
}
});
console.log("objIndex", objIndex)
this.setState({photos: objIndex})
}
updatePhotoObj = (event) => {
const { value, id } = event.target;
console.log("value", value)
console.log("event.target", event.target)
const objIndex = this.state.photos.map((obj, index) => {
if(index == id){
obj.title = value
}
return obj
});
this.setState({photos: objIndex})
}
handleInputChangeRadio = (event) => {
const { name, id} = event.target;
console.log("GET HERE!", name)
console.log("GET HERE!", id)
const objIndex = this.state.photos.map((obj, index) => {
if(index == id){
obj.thumbnail = true
}else{
obj.thumbnail = false
}
return obj
});
this.setState({photos: objIndex})
}
handleInputChangeOne = (event) => {
const { name, id} = event.target;
console.log("GET HERE!", name)
console.log("GET HERE!", id)
const objIndex = this.state.photos.map((obj, index) => {
if(index == id){
obj.image1 = true
}else{
obj.image1 = false
}
return obj
});
this.setState({photos: objIndex})
}
handleInputChangeTwo = (event) => {
const { name, id} = event.target;
console.log("GET HERE!", name)
console.log("GET HERE!", id)
const objIndex = this.state.photos.map((obj, index) => {
if(index == id){
obj.image2 = true
}else{
obj.image2 = false
}
return obj
});
this.setState({photos: objIndex})
}
render() {
const table = {
width: '100%',
paddingTop: '20px'
}
return (
<>
<div class="col-md-12">
<form onSubmit={this.onSubmit}>
<div class="form-group">
<label>Title</label>
<input
class="form-control"
type="text"
name="title"
placeholder="Enter title"
value={this.state.title}
onChange={this.handleInputChange}
/>
</div>
<div class="form-group">
<label>Description</label>
<textarea
class="form-control"
type="text"
rows="10"
name="description"
placeholder="Enter title"
value={this.state.description}
onChange={this.handleInputChange}
/>
</div>
<div class="form-group">
<label for="inputTag">Tag</label>
<select id="inputTag" class="form-control"
value={this.state.tagName}
name="tagName"
onChange={this.handleInputChange}
>
<option value="" disabled selected>Please Choose...</option>
{this.state.tags.map(s =>
<option selected>{s.name}</option>
)}
</select>
</div>
<div class="form-row">
<label>New Photo</label>
</div>
<div class="form-row">
<input type="file" id="myFile" onChange={this.singleFileChangedHandler}/>
<button className="btn btn-secondary" onClick={this.singleFileUploadHandler}>Add Photo</button>
</div>
<div class="form-row">
{this.state.photos.length > 0 ?
<div style={table}>
<div class="table-responsive-sm">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">photos</th>
<th scope="col"></th>
<th scope="col"></th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{this.state.photos.map((x, index) => {
return (
<>
<tr>
<td > <img src={x.photo} alt=""/></td>
<td></td>
<td></td>
<td></td>
<td>
<button class="btn" onClick={()=> this.removePhoto(index)}>remove</button>
<div class="form-check">
<input
class="form-check-input"
type="radio" name="thumb" id={index}
name="thumb"
checked={x.thumbnail}
onChange={this.handleInputChangeRadio}
/>
<label class="form-check-label" for="thumb">
Thumbnail
</label>
</div>
<div class="form-check">
<input
class="form-check-input"
type="radio" name="one" id={index}
name="one"
checked={x.image1}
onChange={this.handleInputChangeOne}
/>
<label class="form-check-label" for="one">
Image 1
</label>
</div>
<div class="form-check">
<input
class="form-check-input"
type="radio" name="two" id={index}
name="two"
checked={x.image2}
onChange={this.handleInputChangeTwo}
/>
<label class="form-check-label" for="two">
Image 2
</label>
</div>
</td>
</tr>
<tr>
<input
class="form-control"
type="text"
value={x.title}
id={index}
onChange={this.updatePhotoObj}
/>
</tr>
</>
);
})}
</tbody>
</table>
</div>
</div>
:
null
}
</div>
<div class="modal-footer">
<input type="submit" value="Submit" class="btn btn-primary"/>
<button type="button" class="btn btn-secondary" data-dismiss="modal" onClick={this.handleClose}>Close</button>
</div>
</form>
</div>
</>
);
}
}
Most importantly you have to add type to the button
<button type="button" class="btn" onClick={()=> this.removePhoto(index)}>remove</button>
Buttons Without type inside form is by default type="submit" so when you click on it, it will submit the form
I think there is better way to filter the array
const filterdPhotos = photos.filter((obj, index) => {
return index != i;
});
this.setState({photos: filterdPhotos})
The reason it triggers your onSubmit is because you have a button inside a form with no specified type.
I believe if you simply declare type="button" to prevent the browser from assuming it's a submit button you should be good to go.
So you would want:
<button class="btn" type="button" onClick={()=> this.removePhoto(index)}>remove</button>
Related
I'm trying to save information in a table, which also has a field of type varbinary(max) (an image) (SQL Server)
class AddDoctor extends Component {
state = {
file: null,
name: "",
phoneNumber: "",
email: "",
status: "Active",
specialty: "",
specialities: [],
};
componentDidMount() {
const URL = "http://localhost:55317/api/TSpecialties";
ApiService.get(URL)
.then((data) => this.setState({ specialities: data }))
.catch((err) => console.log(err));
}
imgClick = () => {
const file = document.querySelector("#id-file");
file.click();
};
handleChange = (e) => {
const state = this.state;
state[e.target.name] = e.target.value;
this.setState({
...state,
});
};
handleFileChange = (event) => {
this.setState({
file: URL.createObjectURL(event.target.files[0]),
});
};
handleSubmit = (e) => {
e.preventDefault();
const URL = "http://localhost:55317/api/TDoctors/";
const DATA = {
doctorName: this.state.name,
doctorProfileImg: this.state.file,
doctorPhoneNumber: this.state.phoneNumber,
doctorEmail: this.state.email,
doctorStatus: this.state.status,
doctorSpecialtyId: Number(this.state.specialty),
};
let formData = new FormData();
formData.append("doctorProfileImg", DATA.doctorProfileImg);
formData.append("doctorName", DATA.doctorName);
formData.append("doctorEmail", DATA.doctorEmail);
formData.append("doctorPhoneNumber", DATA.doctorPhoneNumber);
formData.append("doctorStatus", DATA.doctorStatus);
formData.append("doctorSpecialtyId", DATA.doctorSpecialtyId);
const options = {
method: "POST",
body: formData
};
fetch(URL, options)
.then(res => console.log(res))
.catch(err => console.log("ERR: " + err))
};
render() {
return (
<div>
<form className="row g-3" onSubmit={this.handleSubmit}>
<div className="col-md-6">
<label htmlFor="name" className="form-label">
Name
</label>
<input
type="text"
className="form-control"
id="name"
name="name"
onChange={this.handleChange}
placeholder="Input your name"
/>
</div>
<div className="col-md-6">
<label htmlFor="email" className="form-label">
Email
</label>
<input
type="text"
onChange={this.handleChange}
name="email"
className="form-control"
id="email"
/>
</div>
<div className="col-md-6">
<label className="mb-2" htmlFor="phoneNumber">
Phone Number
</label>
<div className="input-group mb-2 mr-sm-2">
<div className="input-group-prepend">
<div className="input-group-text">+51</div>
</div>
<input
type="text"
onChange={this.handleChange}
className="form-control"
id="phoneNumber"
name="phoneNumber"
placeholder="Phone Number"
/>
</div>
</div>
<div className="col-md-12">
<label htmlFor="specialty" className="form-label">
Specialty
</label>
{/* */}
<select
id="specialty"
name="specialty"
onChange={this.handleChange}
className="form-select"
>
<option defaultValue>Choose...</option>
{this.state.specialities.map((sp) => (
<option value={sp.specialtyId}>
{sp.specialtyName}
</option>
))}
</select>
{/* */}
</div>
<div className="col-12 my-5">
<button
type="submit"
className="btn btn-outline-success w-100"
>
Save
</button>
</div>
</form>
<div className="col mx-5" style={{ minWidth: "250px" }}>
<img
src={ this.state.file}
id="img-select"
onClick={this.imgClick}
className="img-fluid img-thumbnail"
alt="doctor-img"
/>
<input
type="file"
style={{ display: "none" }}
onChange={this.handleFileChange}
id="id-file"
/>
</div>
</div>
);
}
}
Controller POST:
// POST: api/TDoctors
[HttpPost]
public async Task<IActionResult> PostTDoctor([FromBody] TDoctor tDoctor)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.TDoctor.Add(tDoctor);
await _context.SaveChangesAsync();
return CreatedAtAction("GetTDoctor", new { id = tDoctor.DoctorId }, tDoctor);
}
response on console developer tools when submit form:
and...
I have searched a lot of information and I cannot find the solution. I tried placing the multipart/form-data and it doesn't work either. I hope you can help me please.
Saving binary data to a SQL table is not a good practice, please use Azure Blob storage or some other storage service to store the files and just save the path of the file in the database column of a table
I have a form that contain 3 text box 2 of them are input and third one get the value from the map component. when i select the map address it shows in next map address text box also, for clear view my text box is like :
[1 branch][1]
when I click add branch the three text is added again but the map value is presetted like this:
[after add branch][2]
My code is :
import React from 'react';
import '../css/test.css';
import Header from './Header';
import SimpleModal from './modal';
import Branch from './branch';
import axios from 'axios';
import { Link } from 'react-router-dom';
const TOUR_STEPS = [
{
target: ".step1",
content: "View the cart you’ve added here",
disableBeacon: true,
},
{
target: ".step2",
content:
"View the cart you’ve added here",
},
{
target: ".step3",
content: "Contact the developer",
},
{
target: ".step4",
content: "We accept returns after 14 days max",
},
];
class Communication extends React.Component {
constructor(props) {
super(props);
this.state = {
input: {},
errors: {},
counter:0,
values: [
{ address1: { value: ''}, address2: { value: ''} }
]
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.appendDiv = this.appendDiv.bind(this);
this.mapFunctionHere = this.mapFunctionHere.bind(this);
}
handleChange(event) {
let input = this.state.input;
input[event.target.name] = event.target.value;
this.setState({
input
});
}
handleChangeInput = (counter, key, value) => {
const newValues = [...this.state.values]
newValues[counter][key].value = value
this.setState({ values: newValues })
}
mapFunctionHere(param) {
this.setState({
MapAddr:param[0],
});
}
handleSubmit(event) {
event.preventDefault();
if(!this.validate()){
console.log(this.state.values);
let input = {};
input["phoneNumber"] = "";
input["password"] = "";
this.setState({input:input});
console.log(this.state.MapAddr);
console.log(this.state.input);
const formData = new FormData();
formData.append("mobile", this.state.input.phoneNumber);
formData.append("password",this.state.input.password);
formData.append("fcm_token", 1);
formData.append("device_id", 1);
formData.append("source", 1);
formData.append("device_name", 1);
formData.append("os_version", 1);
axios({
method: 'post',
url: 'url',
data: formData,
config: { headers: {'Content-Type': 'multipart/form-data','Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS', }}
})
.then(function (response) {
//handle success
console.log(response);
if(response.data.result === true){
window.location.href = "/Detail";
}
else{
alert(response.data.msg);
}
console.log(response.data.msg);
console.log(response.data.result);
})
.catch(function (response) {
console.log(response);
});
}
};
renderBranches = () => {
const { counter } = this.state
const result = []
for (let i = 0; i <= counter; i++) {
result.push(this.renderBranch(i))
}
return result
}
appendDiv = () => {
this.setState({
counter: this.state.counter + 1,
values: [
...this.state.values,
{ address1: { value: ''}, address2: { value: '' } }
]
})
}
validate(){
let input = this.state.input;
let errors = {};
let isValid = true;
if (!input["fullname"]) {
isValid = false;
errors["fullname"] = "Please enter your fullname.";
}
if (typeof input["fullname"] !== "undefined") {
const re = /^\S*$/;
if(input["fullname"].length < 1 || !re.test(input["fullname"])){
isValid = false;
errors["fullname"] = "Please enter fullname.";
}
}
if (!input["address1"]) {
isValid = false;
errors["address1"] = "Please enter your address.";
}
if (typeof input["address1"] !== "undefined") {
if(input["address1"].length < 4){
isValid = false;
errors["address1"] = "Please add at least 4 address.";
}
}
if (!input["address2"]) {
isValid = false;
errors["address2"] = "Please enter your address.";
}
if (typeof input["address2"] !== "undefined") {
if(input["address2"].length < 4){
isValid = false;
errors["address2"] = "Please add at least 4 address.";
}
}
if (!input["address3"]) {
isValid = false;
errors["address3"] = "Please enter your address.";
}
if (typeof input["address3"] !== "undefined") {
if(input["address3"].length < 4){
isValid = false;
errors["address3"] = "Please add at least 4 address.";
}
}
if (!input["branch"]) {
isValid = false;
errors["branch"] = "Please Enter No of branch.";
}
if (typeof input["branch"] !== "undefined") {
if(input["branch"].length < 6){
isValid = false;
errors["branch"] = "Please Enter No of branch.";
}
}
this.setState({
errors: errors
});
return isValid;
}
renderBranch = counter => {
const { values,MapAddr } = this.state
return (
<>
<div className="form-group">
<label>Store Address</label>
<input type="text"
value={values[counter].address1.value}
onChange={event => this.handleChangeInput(counter, 'address1', event.target.value)}
className="form-control code"
name="address1"
placeholder="Pincode"
/>
<span className="form-text" id="errtext">
{values[counter].address1.error}
</span>
</div>
<div className="form-group">
<div className="row">
<div className="col">
<input type="text" className="form-control code"
value={values[counter].address2.value}
onChange={event => this.handleChangeInput(counter, 'address2', event.target.value)}
name="address2"
placeholder="address" />
<span className="form-text" id="errtext">
{values[counter].address2.error}
</span>
</div>
<div className="col-md-auto">
<p style={{margin:"5px"}}>and</p>
</div>
<div className="col">
<SimpleModal className="form-control" mapFunctionHere={this.mapFunctionHere}/>
</div>
</div>
</div>
<div className="form-group">
<input type="text"
className="form-control code"
value={MapAddr}
onChange={event => this.handleChangeInput(counter, 'address3', MapAddr)}
name="address3"
placeholder="address"
readOnly
/>
<span className="form-text" id="errtext">
</span>
</div>
</>
)
}
render() {
var rows = [];
for (var i = 0; i < 1; i++) {
rows.push(<Branch key={i} />);
}
return <>
<Header data={TOUR_STEPS}/>
<div id="kt_body" className="header-fixed header-mobile-fixed subheader-enabled subheader-fixed aside-enabled aside-fixed aside-minimize-hoverable page-loading">
<div className="d-flex flex-column-fluid">
<div className="container">
<div className="card card-custom">
<div className="card-body p-0">
<div className="wizard wizard-3" id="kt_wizard_v3" data-wizard-state="step-first" data-wizard-clickable="true">
<div className="wizard-nav">
<div className="wizard-steps px-8 py-8 px-lg-15 py-lg-3">
<div className="wizard-step full" data-wizard-type="step">
<div className="wizard-label">
<h3 className="wizard-title">
<span>1.</span>Verify Your Details</h3>
<div className="wizard-bar"></div>
</div>
</div>
<div className="wizard-step full" data-wizard-type="step">
<div className="wizard-label">
<h3 className="wizard-title">
<span>2.</span>classification</h3>
<div className="wizard-bar"></div>
</div>
</div>
<div className="wizard-step full" data-wizard-type="step" >
<div className="wizard-label">
<h3 className="wizard-title">
<span>3.</span>Authentication</h3>
<div className="wizard-bar"></div>
</div>
</div>
<div className="wizard-step full" data-wizard-type="step" data-wizard-state="current">
<div className="wizard-label">
<h3 className="wizard-title">
<span>4.</span>Communication</h3>
<div className="wizard-bar"></div>
</div>
</div>
<div className="wizard-step full" data-wizard-type="step">
<div className="wizard-label">
<h3 className="wizard-title">
<span>5.</span>Documentaion</h3>
<div className="wizard-bar"></div>
</div>
</div>
<div className="wizard-step mob" data-wizard-type="step" data-wizard-state="current">
<div className="wizard-label">
<h3 className="wizard-title">
<span>(4/5)</span>Communication</h3>
<div className="wizard-bar"></div>
</div>
</div>
</div>
</div>
<div className="row justify-content-center py-10 px-8 py-lg-12 px-lg-10">
<div className="col-xl-12 col-xxl-7">
<form className="form" id="kt_form">
<div className="pb-5" data-wizard-type="step-content" data-wizard-state="current">
<h4 className="mb-10 font-weight-bold text-dark">Business Communication Details</h4>
<div className="row ">
<div className="col-xl-6">
<div className="form-group">
<label>Store/Brand Name</label>
<input type="text"
value={this.state.input.fullname}
onChange={this.handleChange}
className="form-control code"
name="fullname" placeholder="Brand Name" />
<span className="form-text" id="errtext">{this.state.errors.fullname}</span>
</div>
<div className="form-group">
<label>Does it has Branches ?</label>
<div className="checkbox-inline">
<label className="checkbox">
<input type="checkbox" name="Checkboxes3"/>
<span></span>
Yes
</label>
<label >
<input type="text"
className="form-control code"
name="branch" value={this.state.input.branch}
onChange={this.handleChange}
placeholder="Pincode" />
</label>
</div>
<span className="form-text" id="errtext">{this.state.errors.branch}</span>
</div>
{this.renderBranches()}
<div className="toolti">
<input type="button" className="addbranch" onClick={this.appendDiv} value="Add Branch" />
<span className="tooltitext">You can add branches even after registration
from your dashboard</span>
</div>
</div>
</div>
</div>
<div className="d-flex justify-content-between border-top mt-5 pt-10">
<div className="mr-2">
{/* <button type="button" className="btn btn-light-primary font-weight-bolder text-uppercase px-9 py-4">Previous</button> */}
<Link to="/authentication" class="btn btn-primary font-weight-bolder text-uppercase px-9 py-4" data-wizard-type="action-next" style={{backgroundColor:"#3951A0",borderColor:"#3951A0"}}>Previous</Link>
</div>
<div>
{/* <Link to="/documentation" class="btn btn-primary font-weight-bolder text-uppercase px-9 py-4" data-wizard-type="action-next" style={{backgroundColor:"#3951A0",borderColor:"#3951A0"}}>Next</Link> */}
<button type="button" className="btn btn-primary font-weight-bolder text-uppercase px-9 py-4"
onClick={this.handleSubmit}
style={{backgroundColor:"#3951A0",borderColor:"#3951A0"}}>Next</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</>
}
}
export default Communication;
In select on map i am calling a modal my modal code is:
class SimpleModal extends React.Component {
//export default function SimpleModal() {
constructor(props) {
super(props);
//Set initial state
this.state = {
setOpen: false,
name: ""
}
this.handleOpen = this.handleOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
this.someFunctionHere = this.someFunctionHere.bind(this);
}
// const classes = useStyles();
// // getModalStyle is not a pure function, we roll the style only on the first render
// const [modalStyle] = React.useState(getModalStyle);
// //const [open, setOpen] = React.useState(false);
someFunctionHere(param) {
this.props.mapFunctionHere(param);
}
handleOpen() {
this.setState({
setOpen: true
});
};
handleClose(){
this.setState({
setOpen: false
});
};
render()
{
return <>
<div style={{position:"absolute"}}>
<button type="button" className="form-control map" onClick={this.handleOpen}>
Select on Map
</button>
<Modal
open={this.state.setOpen}
onClose={this.handleClose}
aria-labelledby="simple-modal-title"
aria-describedby="simple-modal-description"
>
<div className="paper" >
<Map someFunctionHere={this.someFunctionHere} />
{/* <SimpleModal /> */}
<button type="button" style={{height: "43px",width: "138px",
borderRadius: "4px",backgroundColor: "#3951A0",color:'white',border:"none",float:"right"}} onClick={this.handleClose}>
Close
</button>
</div>
</Modal>
</div>
</>
}
}
export default SimpleModal;
In modal i am calling my map :
class Map extends React.Component {
//const Map = () => {
constructor(props) {
super(props);
//Set initial state
this.state = {
addres: '',
defaultLocation: DefaultLocation,
location:DefaultLocation,
zoom:DefaultZoom
}
this.handleChangeLocation = this.handleChangeLocation.bind(this);
}
handleChangeLocation (lat, lng){
this.setState({
location: {lat:lat, lng:lng},
})
console.log(lat,lng)
axios.get(`url`)
.then(res => {
console.log(res.data.results[0].formatted_address);
// const numbers = [1, 2, 3, 4, 5];
const setaaddres = [res.data.results[0].formatted_address,lat,lng];
this.setState({addres: res.data.results[0].formatted_address});
this.props.someFunctionHere(setaaddres);
})
}
handleChangeZoom (newZoom){
this.setState({
zoom: newZoom,
})
}
render() {
return (
<>
<div>
<input type='text' style={{width:"100%"}} defaultValue={this.state.addres} />
<MapPicker defaultLocation={this.state.defaultLocation}
zoom={this.state.zoom}
style={{height:'500px'}}
onChangeLocation={this.handleChangeLocation}
onChangeZoom={this.handleChangeZoom}
apiKey='AIzaSyB-tpDLb6LG767qc9ttvDrf23IOqLxheXk'/>
</div>
</>
);
}
}
;
export default Map;
How to get different map values for different text box ?
[1]: https://i.stack.imgur.com/P6LX9.png
[2]: https://i.stack.imgur.com/jpT01.png
I am working on a very basic form in React, and I am having difficulty getting the data to submit properly. In this current setup, only the 'content' field is submitting correctly, eventhough the firstName, lastName, and email are all written the same. The radio buttons and dropdown are also not submitting. Any ideas?
import React from "react";
import axios from "axios";
import '../ticket.min.css'
class Ticket extends React.Component {
constructor(props) {
super(props);
this.state = {
firstName: '',
lastName: '',
email: '',
content: ''
}
this.ticketName = React.createRef();
this.state = { tickets: [] };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.onValueChange = this.onValueChange.bind(this);
}
handleChange = event => {
this.setState({ value: event.target.value });
}
handleSubmit = event => {
alert('Your ticket has been submitted');
event.preventDefault();
}
onValueChange = event => {
this.setState({
selectedOption: event.target.value
});
}
addTicket = () => {
let url = "http://localhost:8080/tickets";
axios.post(url, { firstName: this.ticketName.current.value, lastName: this.ticketName.current.value, email: this.ticketName.current.value, content: this.ticketName.current.value }).then(response => {
this.ticketName.current.value = "";
alert('Your ticket has been submitted');
});
};
getData = () => {
let url = "http://localhost:8080/tickets";
axios.get(url).then(response => this.setState({ tickets: response.data }));
};
render() {
return (
<div>
<form>
<label>First Name:</label>
<input ref={this.ticketName} type="text" name="firstName"/><br></br>
<label>Last Name:</label>
<input ref={this.ticketName} type="text" name="lastName"/><br></br>
<label>Email:</label>
<input ref={this.ticketName} type="text" name="email"/><br></br>
</form>
<form onSubmit={this.handleSubmit}>
<label>
Select a Category:<br></br>
<select value={this.state.value} onChange={this.handleChange}>
<option value="hardware">Hardware</option>
<option value="software">Software</option>
<option value="internet">Internet</option>
<option value="other">Other</option>
</select>
</label>
</form>
<form>
<label>Please Describe Your Issue:</label><br></br>
<textarea name="content" ref={this.ticketName}/>
</form>
<form onSubmit={this.handleSubmit}>
<label>
Select the Urgency Level:<br></br>
<input type="radio" value="Urgent" checked={this.state.selectedOption === "Urgent"} onChange={this.onValueChange} />Urgent<br></br>
<input type="radio" value="Normal" checked={this.state.selectedOption === "Normal"} onChange={this.onValueChange} />Normal<br></br>
<input type="radio" value="Low Priority" checked={this.state.selectedOption === "Low Priority"} onChange={this.onValueChange} />Low Priority
</label>
</form>
<form>
<button type="button" className="btn btn-primary" onClick={this.addTicket}>Submit</button>
</form>
<h3>Pending Tickets</h3>
<button type="button" className="btn btn-primary" onClick={this.getData}>Show Pending</button>
<ul>
{this.state.tickets.map(p => (
<li key={p.id}>
{p.firstName}{p.lastName}
{/* {p.firstName} : { p.complete ? "complete" : "not complete" } <button type="button" className="btn btn-success">Complete</button><button type="button" className="btn btn-danger">Delete</button> */}
</li>
))}
</ul>
</div>
);
}
}
export default Ticket;
You should put fields in one form element and set the button type to submit.
Well, maybe this is happening because of how I wrote my code. That happen because I am still learning React and all the stuff that I use in the code yesterday.
I am not yet even implementing a react tracker for the loading ui.
The purpose
I want to make a contact form for a course facilitator, but it is much more complex because I need image, checkbox for the program they choose, etc. At least for me that is complex than my blog.
Things that I have tried
I have tried it in development, it works like a charm.
The build also works seeing no problem.
The page after the build can still be visited.
The warning in Chrome
I get a violation in almost all of it. like in click handler, setTimeout, input handler.
The error that I get is three right after I click anything.
Two of the error start with error, but the last one is uncaught error. Maybe that does not matter?
Disclaimer
I may have used some Indonesian language in my code for name and stuff.
import React, { Component } from 'react';
import axios from 'axios';
import Header from "../components/Header"
import Footer from "../components/Footer"
export default class Daftar extends Component{
constructor(){
super();
this.state={
enable: false,
name:'',
email:'',
telepon:'',
program:'',
tempat_lahir:'',
tanggal_lahir:'',
selectedFile:'',
selectedFile1:'',
}
this.handleInputChange = this.handleInputChange.bind(this);
this.handleInputChange1 = this.handleInputChange1.bind(this);
}
handleChange = event =>{
this.setState({ [event.target.name]:event.target.value });
}
handleInputChange(event) {
this.setState({
selectedFile: event.target.files[0],
})
}
handleInputChange1(event) {
this.setState({
selectedFile1: event.target.files[0],
})
}
onChange(event){
let day_list = this.state.program;
let check = event.target.checked;
let checked_day = event.target.value;
if(check){
this.setState({
program: [...this.state.program, checked_day]
})
}else{
var index = day_list.indexOf(checked_day);
if (index > -1) {
day_list.splice(index, 1);
this.setState({
program: day_list
})
}
}
}
componentDidUpdate( prevState) {
if (
( prevState.email !== this.state.email )||
( prevState.name !== this.state.name )||
( prevState.telepon !== this.state.telepon) ||
prevState.program !== this.state.program
) {
if (this.state.email ||
this.state.name ||
this.state.subject ||
this.state.message
) {
this.setState({ enabled: true });
} else {
this.setState({ enabled: false });
}
}
}
handleSubmit = event =>{
event.preventDefault();
const KK = new FormData()
KK.append('kartu-keluarga', this.state.selectedFile)
console.warn(this.state.selectedFile);
const ijazah = new FormData()
ijazah.append('ijazah', this.state.selectedFile1)
console.warn(this.state.selectedFile1);
let url = `${process.env.GATSBY_DIRECTUS_API_URL}/gemaclc/items/pendaftar?access_token=${process.env.GATSBY_DIRECTUS_TOKEN}`;
let url2 = `${process.env.GATSBY_DIRECTUS_API_URL}/gemaclc/files?access_token=${process.env.GATSBY_DIRECTUS_TOKEN}`;
let id_ijazah;
let id_item;
let id_kk;
axios.post(url, {
status:"published",
nama: this.state.name,
email: this.state.email,
telepon: this.state.telepon,
program_yang_dipilih: this.state.program,
tanggal_lahir: this.state.tanggal_lahir,
tempat_lahir: this.state.tempat_lahir,
})
.then(res => {
console.log(res)
id_item = res.data.data.id;
return axios.post(url2, KK, )
})
.then(res => {
console.log(res)
console.log(res.data.data.id)
id_kk = res.data.data.id;
return axios.post(url2, ijazah, )
})
.then(res => {
console.log(res.data.data.id)
id_ijazah = res.data.data.id;
console.log(id_ijazah)
return axios( `${process.env.GATSBY_DIRECTUS_API_URL}/gemaclc/items/pendaftar/${id_item}?access_token=${process.env.GATSBY_DIRECTUS_TOKEN}`,
{
method:"patch",
data :{
kartu_keluarga: id_kk,
ijazah:id_ijazah
},
})
})
.then(res =>{
console.log(res)
})
.catch(error => {
console.log(error)
});
};
render(){
let form = "daftar-form"
let div = "daftar-div"
let div1 = "daftar-div1"
let label1 = "daftar-label1"
let label2 = "daftar-label2"
let label3 = "daftar-label3"
let checkbox = "daftar-checkbox"
let email = "daftar-email"
let nama = "daftar-nama"
let p1 = "daftar-p1"
let submitDisable = "daftar-submit-disable"
let submit = "daftar-submit"
let programDiv = "daftar-program-div"
return(
<div>
<Header/>
<div className={div}>
<div className={div1}>
<h1>Formulir Pendaftaran </h1>
<form onSubmit={this.handleSubmit} className={ form}>
<label className={label1}>
<span>
<p className={p1}> Nama : </p>
</span>
<input type="username" name="name" onChange={this.handleChange}
className={nama}
/>
</label>
<label className={label2}>
<span>
<p className={p1}> Email : </p>
</span>
<input type="email" name="email" onChange={this.handleChange}
className={email}
placeholder="name#location.com"/>
</label>
<label className={label3}>
<span>
<p className={p1}> telepon : </p>
</span>
<input type="tel" name="telepon" onChange={this.handleChange} className={nama}
/>
</label>
<label className={label3}>
<span>
<p className={p1}> Tempat Lahir : </p>
</span>
<input type="text" name="tempat_lahir" onChange={this.handleChange} className={nama}
/>
</label>
<label className={label3}>
<span>
<p className={p1}> Tanggal Lahir : </p>
</span>
<input type="date" name="tanggal_lahir" onChange={this.handleChange} className={nama}
/>
</label>
<div className={programDiv}>
<h3>Program yang Di pilih :</h3>
<label >
<input type="checkbox" onChange={this.onChange.bind(this)} name="program" className={checkbox}value="1"/>
<span>
<p className={p1}> paket A </p>
</span>
</label>
<label >
<input type="checkbox" onChange={this.onChange.bind(this)} name="program" className={checkbox}value="2"/>
<span>
<p className={p1}> paket B</p>
</span>
</label>
<label >
<input type="checkbox" onChange={this.onChange.bind(this)} name="program" className={checkbox}value={3}/>
<span>
<p className={p1}> paket C </p>
</span>
</label>
<label >
<input type="checkbox" onChange={this.onChange.bind(this)} name="program" className={checkbox}value={4}/>
<span>
<p className={p1}> English Regular 3 bulan </p>
</span>
</label>
<label >
<input type="checkbox" onChange={this.onChange.bind(this)} name="program" className={checkbox}value={5}/>
<span>
<p className={p1}> English Camp </p>
</span>
</label>
<label >
<input type="checkbox" onChange={this.onChange.bind(this)} name="program" className={checkbox}value={6}/>
<span>
<p className={p1}> English Private </p>
</span>
</label>
</div>
<div >
<div >
<br /><br />
<br />
<div >
<div >
<label className="text-white"> Kartu keluarga:</label>
<input type="file" name="upload_file"
onChange={this.handleInputChange} />
</div>
</div>
<div >
<div >
<label >ijazah :</label>
<input type="file" name="upload_file"
onChange={this.handleInputChange1} />
</div>
</div>
</div>
</div>
{this.state.enabled?<input type="submit" value="Kirim" className={submit}
/>:<input type="submit" value="Kirim" className={submitDisable} disabled/>}
</form>
<div><pre>{JSON.stringify(this.state.program) }</pre></div>;
</div>
</div>
<Footer/>
</div>
)
}
}
i found it, i just update from
componentDidUpdate( prevState) {
if (
( prevState.email !== this.state.email )||
( prevState.name !== this.state.name )||
( prevState.telepon !== this.state.telepon) ||
prevState.program !== this.state.program
) {
if (this.state.email ||
this.state.name ||
this.state.subject ||
this.state.message
) {
this.setState({ enabled: true });
} else {
this.setState({ enabled: false });
}
}
}
to this
componentDidUpdate(prevProps, prevState) {
if (
( prevState.email !== this.state.email )||
( prevState.name !== this.state.name )||
( prevState.telepon !== this.state.telepon) ||
prevState.program_yang_dipilih !== this.state.program_yang_dipilih
) {
if (this.state.email ||
this.state.name ||
this.state.telepon ||
this.state.program_yang_dipilih
) {
this.setState({ enabled: true });
} else {
this.setState({ enabled: false });
}
}
}
I am created a dynamic form in react.js but i can not type anything value in input because onchnage function not working i don't know why i tried a lot of times but i am getting failed and adding form and deleting form is working all right only input value not working here is my code and codesandbox link https://codesandbox.io/s/reactdynamicform-02cho .
import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
inputFields: [
{
firstName: "",
lastName: ""
}
]
};
}
handleAddFields = () => {
const values = this.state.inputFields;
values.push({ firstName: "", lastName: "" });
this.setState({
values
});
};
handleRemoveFields = index => {
const values = this.state.inputFields;
values.splice(index, 1);
this.setState({
values
});
};
async onChange(e, index) {
if (
["firstName","lastName"].includes(e.target.name)
) {
let cats = [...this.state.inputFields];
cats[index][e.target.name] = e.target.value;
await this.setState({
cats
});
}else{
this.setState({ [e.target.name]: e.target.value.toUpperCase() });
}
console.log(this.state.inputFields);
}
handleSubmit = e => {
e.preventDefault();
console.log("inputFields", this.state.inputFields);
};
render() {
return (
<>
<h1>Dynamic Form Fields in React</h1>
<form onSubmit={this.handleSubmit.bind(this)}>
<div className="form-row">
{this.state.inputFields.map((inputField, index) => (
<div key={`${inputField}~${index}`}>
<div className="form-group col-sm-6">
<label htmlFor="firstName">First Name</label>
<input
type="text"
className="form-control"
id="firstName"
name="firstName"
value={inputField.firstName}
onChange={this.onChange.bind(index)}
/>
</div>
<div className="form-group col-sm-4">
<label htmlFor="lastName">Last Name</label>
<input
type="text"
className="form-control"
id="lastName"
name="lastName"
value={inputField.lastName}
onChange={this.onChange.bind(index)}
/>
</div>
<div className="form-group col-sm-2">
<button
className="btn btn-link"
type="button"
onClick={() => this.handleRemoveFields(index)}
>
-
</button>
<button
className="btn btn-link"
type="button"
onClick={() => this.handleAddFields()}
>
+
</button>
</div>
</div>
))}
</div>
<div className="submit-button">
<button
className="btn btn-primary mr-2"
type="submit"
// onSubmit={this.handleSubmit}
>
Save
</button>
</div>
<br />
<pre>{JSON.stringify(this.state.inputFields, null, 2)}</pre>
</form>
</>
);
}
}
export default App;
You approach is not the correct. Use object to contain form values
state = {
inputFields: { firstName: '', lastName: '' }
}
onChange = (e) => {
const { name, value } = e.target;
this.setState(prevState => ({ inputFields: { ...prevState.inputFields, [name]: value } }));
}
// in jsx
<input name="firstName" onChange={this.onChange} />
try this
onChange={(e)=>{this.onChange(e, index)}}
instead of
onChange={this.onChange.bind(index)}
1) Since your inputFields state is an array, you can't just call this.state.inputFields.firstName and even less inputField.firstName.
You have to call this.state.inputsFields[0].firstName.
2) If you want the index AND the event, you have to pass the onChange event like this :
<input
type="text"
className="form-control"
id="lastName"
name="lastName"
onChange={event => this.handleChange(event, index)}
/>
handleChange = (event, index) => {
console.log(event.currentTarget.value, index);
};
// output : {whatever you type} {index of the form}
// exemple : "hello 1"