Unable to get form data after setState - javascript

I am trying to send form data after submitting to the firebase database using redux in my react application, but I am unable to send the state so I tried tracking form data by console.log but the form data is empty. I am able to console log params but not this.state
Below is the code.
I am using redux in this app. createUser is my action
import React, { Component } from "react";
import { connect } from "react-redux";
import { createUser } from "../store/actions/userActions";
class UserForm extends Component {
constructor(props) {
super(props);
this.state = { form: [], alert: false, alertData: {} };
this.submitMessage = this.submitMessage.bind(this);
}
submitMessage = e => {
e.preventDefault();
const params = {
name: this.inputName.value,
email: this.inputEmail.value,
city: this.inputCity.value,
age: this.inputAge.value
};
this.setState({ form: params });
console.log(params);
console.log("-----------");
console.log(this.state);
this.props.createUser(this.state);
};
render() {
return (
<div className="container">
<div
className="row"
>
User
</div>
<div className="container" style={{ padding: `10px 0px` }} />
<div className="row">
<div className="col-sm-4">
<h2>Contact Form</h2>
<form onSubmit={this.submitMessage} ref="contactForm">
<div className="form-group">
<label htmlFor="name">Name</label>
<input
type="text"
className="form-control"
id="name"
placeholder="Name"
ref={name => (this.inputName = name)}
/>
</div>
<div className="form-group">
<label htmlFor="emai1">Email</label>
<input
type="email"
className="form-control"
id="email"
placeholder="Email"
ref={email => (this.inputEmail = email)}
/>
</div>
<div className="form-group">
<label htmlFor="city">City</label>
<select
className="form-control"
id="city"
ref={city => (this.inputCity = city)}
>
<option value="India">India</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
<option value="Germany">Germany</option>
</select>
</div>
<div className="form-group">
<label htmlFor="age">Age</label>
<input
type="number"
className="form-control"
id="age"
placeholder="Age"
ref={age => (this.inputAge = age)}
/>
</div>
<button type="submit" className="btn btn-primary">
Send
</button>
</form>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {};
};
const mapDispatchToProps = dispatch => {
return {
createUser: user => dispatch(createUser)
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserForm);

Due to setState is asynchronous you can access the changed state in a callback which you can pass as a second param to setState method. Please read more about setState
submitMessage = e => {
e.preventDefault();
const params = {
name: this.inputName.value,
email: this.inputEmail.value,
city: this.inputCity.value,
age: this.inputAge.value
};
this.setState({ form: params }, () => {
console.log(params);
console.log("-----------");
console.log(this.state);
this.props.createUser(this.state);
});
};

You call createUser before setState is finished. Why use the state anyway? I would suggest:
submitMessage = e => {
e.preventDefault();
const params = {
name: this.inputName.value,
email: this.inputEmail.value,
city: this.inputCity.value,
age: this.inputAge.value
};
this.props.createUser(params);
};

There is you are missing two things,
Set state is async in nature so after set state, you must use call back to access it.
You are not passing form data ie. Params to createUser
Solution :
import React, { Component } from "react";
import { connect } from "react-redux";
import { createUser } from "../store/actions/userActions";
class UserForm extends Component {
constructor(props) {
super(props);
this.state = { form: [], alert: false, alertData: {} };
this.submitMessage = this.submitMessage.bind(this);
}
submitMessage = e => {
e.preventDefault();
const params = {
name: this.inputName.value,
email: this.inputEmail.value,
city: this.inputCity.value,
age: this.inputAge.value
};
this.setState({ form: params },()=>{
this.props.createUser(this.state);
});
};
render() {
return (
<div className="container">
<div
className="row"
>
User
</div>
<div className="container" style={{ padding: `10px 0px` }} />
<div className="row">
<div className="col-sm-4">
<h2>Contact Form</h2>
<form onSubmit={this.submitMessage} ref="contactForm">
<div className="form-group">
<label htmlFor="name">Name</label>
<input
type="text"
className="form-control"
id="name"
placeholder="Name"
ref={name => (this.inputName = name)}
/>
</div>
<div className="form-group">
<label htmlFor="emai1">Email</label>
<input
type="email"
className="form-control"
id="email"
placeholder="Email"
ref={email => (this.inputEmail = email)}
/>
</div>
<div className="form-group">
<label htmlFor="city">City</label>
<select
className="form-control"
id="city"
ref={city => (this.inputCity = city)}
>
<option value="India">India</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
<option value="Germany">Germany</option>
</select>
</div>
<div className="form-group">
<label htmlFor="age">Age</label>
<input
type="number"
className="form-control"
id="age"
placeholder="Age"
ref={age => (this.inputAge = age)}
/>
</div>
<button type="submit" className="btn btn-primary">
Send
</button>
</form>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return {};
};
const mapDispatchToProps = dispatch => {
return {
createUser: user => dispatch(createUser(user))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(UserForm);

Related

How to convert Class component to function on react

I have a customer feedback page or rather a contact page. There are a few in there. The page is written in JavaScript, React in the class component. I want to convert it to a functional component.
Below I will throw source code off the page
import React, { Component } from "react";
import { Button, Form, FormGroup, Label, Input, FormText } from "reactstrap";
import axios from "axios";
class Contacts extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
subject: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
//console.log(`${e.target.name}:${e.target.value}`);
};
async handleSubmit(e) {
e.preventDefault();
const { name, email, subject } = this.state;
const form = await axios.post("/api/form", {
name,
email,
subject
});
}
render() {
return (
<Form className="col-xs-12 col-md-6" onSubmit={this.handleSubmit}>
<FormGroup>
<Label for="name">name:</Label>
<Input type="text" name="name" onChange={this.handleChange} />
</FormGroup>
<FormGroup>
<Label for="exampleEmail">Email:</Label>
<Input type="email" name="email" onChange={this.handleChange} />
</FormGroup>
<FormGroup>
<Label for="subject">Subject:</Label>
<Input type="textarea" name="subject" onChange={this.handleChange} />
</FormGroup>
<Button>Submit</Button>
</Form>
);
}
}
export default Contacts;
1- first create a functional component like below:
2- add some hooks for the state:
3- Refactor functions in a new way:
4- At the end add the return section.
Finally you have something like this:
export default function Contacts() {
const [state, setState] = useState({
name: '',
email: '',
subject: '',
});
const handleChange = (e) => {
setState({ [e.target.name]: e.target.value });
//console.log(`${e.target.name}:${e.target.value}`);
};
const handleSubmit = async (e) => {
e.preventDefault();
const { name, email, subject } = state;
const form = await axios.post('/api/form', {
name,
email,
subject,
});
};
return (
<Form className="col-xs-12 col-md-6" onSubmit={handleSubmit}>
<FormGroup>
<Label for="name">name:</Label>
<Input type="text" name="name" onChange={handleChange} />
</FormGroup>
<FormGroup>
<Label for="exampleEmail">Email:</Label>
<Input type="email" name="email" onChange={handleChange} />
</FormGroup>
<FormGroup>
<Label for="subject">Subject:</Label>
<Input type="textarea" name="subject" onChange={handleChange} />
</FormGroup>
<Button>Submit</Button>
</Form>
);
}
const Contacts = (props) => {
const [name, setName] = useState();
const [email, setEmail] = useState();
const [subject, setSubject] = useState();
const handleChange = useCallback((setState, event) => {
setState(event.target.value);
}, []);
const handleSubmit = useCallback(async () => {
const response = await axios.post("/api/form", {
name,
email,
subject
});
console.log(response)
}, [name, email, subject]);
return (
<Form className="col-xs-12 col-md-6" onSubmit={handleSubmit}>
<FormGroup>
<Label for="name">name:</Label>
<Input type="text" name="name" onChange={handleChange.bind(null, setName)} />
</FormGroup>
<FormGroup>
<Label for="exampleEmail">Email:</Label>
<Input type="email" name="email" onChange={handleChange.bind(null, setEmail)} />
</FormGroup>
<FormGroup>
<Label for="subject">Subject:</Label>
<Input type="textarea" name="subject" onChange={handleChange.bind(null, setSubject)} />
</FormGroup>
<Button>Submit</Button>
</Form>
);
}

React Form values are not reflected on the FORM items for EDIT using class state

I'm pulling data from MongoDB and trying to edit the data but for some reason, my form is not showing the values on the form. Can anyone help to guide me on what I am getting wrong? below is my code for any help why form value are not updated using this.state.job_title as an example:
edit-job.component.js
import React, { Component } from "react";
import axios from "axios";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
export default class EditJob extends Component {
constructor(props) {
super(props);
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangeJob_title = this.onChangeJob_title.bind(this);
this.onChangejob_comp_image = this.onChangejob_comp_image.bind(this);
this.onChangejob_comp_name = this.onChangejob_comp_name.bind(this);
this.onChangejob_description = this.onChangejob_description.bind(this);
this.onChangejob_location = this.onChangejob_location.bind(this);
this.onChangejob_field = this.onChangejob_field.bind(this);
this.onChangeDatejob_closing_date =
this.onChangeDatejob_closing_date.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
username: "",
job_title: "",
job_comp_image: "",
job_comp_name: "",
job_description: "",
job_location: "",
job_field: "",
job_closing_date: new Date(),
users: [],
};
}
componentDidMount() {
//GET CURRENT JOB LISTING TO EDIT
if (this.props.match && this.props.match.params.id) {
axios
.get("http://localhost:5001/jobs/" + this.props.match.params.id)
.then((response) => {
console.log(response.data);
this.setState({
username: response.data.username,
job_title: response.data.job_title,
job_comp_image: response.data.job_comp_image,
job_comp_name: response.data.job_comp_name,
job_description: response.data.job_description,
job_location: response.data.job_location,
job_field: response.data.job_field,
job_closing_date: new Date(response.data.job_closing_date),
});
})
.catch(function (error) {
console.log(error);
});
}
axios
.get("http://localhost:5001/users/")
.then((response) => {
if (response.data.length > 0) {
this.setState({
users: response.data.map((user) => user.username),
});
}
})
.catch((error) => {
console.log(error);
});
}
onChangeUsername(e) {
this.setState({
username: e.target.value,
});
}
//Update user with new username entered by user
onChangeJob_title(e) {
this.setState({
job_title: e.target.value,
});
}
onChangejob_comp_image(e) {
this.setState({
job_comp_image: e.target.value,
});
}
onChangejob_comp_name(e) {
this.setState({
job_comp_name: e.target.value,
});
}
onChangejob_description(e) {
this.setState({
job_description: e.target.value,
});
}
onChangejob_location(e) {
this.setState({
job_location: e.target.value,
});
}
onChangejob_field(e) {
this.setState({
job_field: e.target.value,
});
}
onChangeDatejob_closing_date(job_closing_date) {
this.setState({
job_closing_date: job_closing_date,
});
}
onSubmit(e) {
e.preventDefault();
const job = {
username: this.state.username,
job_title: this.state.username,
job_comp_image: this.state.job_comp_image,
job_comp_name: this.state.job_comp_name,
job_description: this.state.job_description,
job_location: this.state.job_location,
job_field: this.state.job_field,
job_closing_date: new Date(),
};
console.log(job);
axios
.post(
"http://localhost:5001/jobs/update/" + this.props.match.params.id,
job
)
.then((res) => console.log(res.data));
window.location = "/";
}
render() {
const Headerstyle = {
marginTop: "40px",
};
return (
<div style={Headerstyle}>
<h3>Edit Exercise Log</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Username: </label>
<select
UseRef="userInput"
required
className="form-control"
value={this.state.username}
onChange={this.onChangeUsername}
>
{this.state.users.map(function (user) {
return (
<option key={user} value={user}>
{user}
</option>
);
})}
</select>
</div>
<div className="form-group">
<label>Job Title: </label>
<input
type="text"
required
className="form-control"
value={this.state.job_title}
onChange={this.onChangeJob_title}
/>
</div>
<div className="form-group">
<label>Company Image: </label>
<input
type="text"
className="form-control"
value={this.state.job_comp_image}
onChange={this.onChangejob_comp_image}
/>
</div>
<div className="form-group">
<label>Company Name: </label>
<input
type="text"
className="form-control"
value={this.state.job_comp_name}
onChange={this.onChangejob_comp_name}
/>
</div>
<div className="form-group">
<label>Job Description: </label>
<input
type="text"
className="form-control"
value={this.state.job_description}
onChange={this.onChangejob_description}
/>
</div>
<div className="form-group">
<label>Job Location: </label>
<input
type="text"
className="form-control"
value={this.state.job_location}
onChange={this.onChangejob_location}
/>
</div>
<div className="form-group">
<label>Job related field: </label>
<input
type="text"
className="form-control"
value={this.state.job_field}
onChange={this.onChangejob_field}
/>
</div>
<div className="form-group">
<label>Job Closing Date: </label>
<div>
<DatePicker
selected={this.state.job_closing_date}
onChange={this.onChangeDatejob_closing_date}
/>
</div>
</div>
<div className="form-group">
<input
type="submit"
value="Edit Job Listing"
className="btn btn-primary"
/>
</div>
</form>
</div>
);
}
}

ReactJs | Show only the selected value in URL

I am new to reatJS. Can some genius please help me with my issue?
I am developing a e-pharmacy website where I let the users to first select a preferred districts and select a pharmacy from that area. I list out all the districts along with a drop down menu which shows all the pharmacies in that district. Then the user can make orders to the selected pharmacy.
I pass the selected pharmacy Id through the URL when user post an order.
If I had 3 districts, and I have selected a pharmacy from the third district, the URL appears like this:
http://localhost:3000/uploadlist?phmcy=&phmcy=&phmcy=1 (here the id of the selected pharmacy is "1")
The URL shows all the unselected values also. My preference is to display only the selected pharmacy's Id.
I want only the selected value to be displayed. Like this:
http://localhost:3000/uploadlist?phmcy=1
Here is my codes:
The district component: (Where the customer can select a district)
import React,{ Component } from 'react';
//import { Router } from 'react-router-dom/cjs/react-router-dom.min';
import { Link, withRouter } from "react-router-dom";
import './district.css';
import Upload from "./upload.component";
import Districtpharmacy from "./districtpharmacy.component";
class District extends React.Component{
state = {
pharmacy: []
};
render(){
return(
<div className="container">
<div className="container district">
<form action="/uploadlist" method="get">
<div className="row">
<div className="container header">
<h1>Select your District and Nearby Pharmacy</h1>
<p>Please select only one pharmacy</p>
</div>
</div>
<div className="row">
<div className="form-column">
<Districtpharmacy district="Mathara"/>
<Districtpharmacy district="Galle"/>
<Districtpharmacy district="Hambantota"/>
<Districtpharmacy district="Kalutara"/>
<Districtpharmacy district="Colombo"/>
<Districtpharmacy district="Gampaha"/>
<Districtpharmacy district="Rathnapura"/>
<Districtpharmacy district="Kurunegala"/>
</div>
<div className="form-column">
<Districtpharmacy district="Monaragala"/>
<Districtpharmacy district="Anuradhapura"/>
<Districtpharmacy district="Polonnaruwa"/>
<Districtpharmacy district="Kandy"/>
<Districtpharmacy district="Nuwara Eliya"/>
<Districtpharmacy district="Kegalla"/>
<Districtpharmacy district="Matale"/>
<Districtpharmacy district="Badulla"/>
<Districtpharmacy district="Ampara"/>
</div>
<div className="form-column">
<Districtpharmacy district="Puttalam"/>
<Districtpharmacy district="Trincomalee"/>
<Districtpharmacy district="Batticaloa"/>
<Districtpharmacy district="Mannar"/>
<Districtpharmacy district="Vavuniya"/>
<Districtpharmacy district="Mulaitivu"/>
<Districtpharmacy district="Kilinochchi"/>
<Districtpharmacy district="Jaffna"/>
</div>
</div>
<br/>
<button type="submit" >Add</button>
</form>
</div>
</div>
);
}
}
export default withRouter(District);
district.pharmacy component: (where the dropdown menu is returned.)
import React,{ Component } from 'react';
//import { Router } from 'react-router-dom/cjs/react-router-dom.min';
import { Link } from "react-router-dom";
import './district.css';
//import Upload from "./upload.component";
class Districtpharmacy extends React.Component{
state = {
pharmacy: [],
District: this.props.district
};
componentDidMount() {
console.log(this.state)
fetch("https://localhost:44357/api/Pharmacies?field=district&value="+this.props.district)
.then(response => response.json())
.then(pharmacy => this.setState({pharmacy: pharmacy}));
//console.log(this.state)
}
render(){
//console.log(this.state)
const pharm=this.state.pharmacy.map((pharmacies) =>{
return(<option value ={pharmacies.id}>{pharmacies.pharmacyname},{pharmacies.address}</option>)})
return(
<div>
<label class="label" for="district"><span>{this.props.district}</span></label>
<select name="phmcy" className="form-control select-dropdown"><option value="">Select Pharmacy</option>{pharm}</select>
</div>
)
}
}
export default Districtpharmacy
Can someone help me with this?
Edited:
The order posting form:
The parent file: (uploadlist.js)(the "phmcy" value is to be fetched from the url. this file is triggered after selecting the pharmacy)
export default function Uploadlist() {
let myphmcy = (new URLSearchParams(window.location.search)).get("phmcy")
console.log(myphmcy);
const ordersAPI= (url='https://localhost:44357/api/Orders') => {
return {
fetchAll: () => axios.get(url),
create: newRecord => axios.post(url, newRecord),
update: (id, updateRecord) => axios.put(url + id, updateRecord),
delete: id => axios.delete(url+id)
}
}
const addOrEdit = (formData, onSuccess) => {
ordersAPI().create(formData)
.then(res => {
onSuccess();
})
.catch(err => console.log(err.response.data))
}
return (
<div className="row">
<div className="jumbotron jumbotron-fluid py-4 "></div>
<div className="container text">
<h1 className="display-4"> Order Register</h1>
</div>
<div className="col-md-4 offset-3">
<Upload //this is the child component where the order form is built.
addOrEdit = {addOrEdit}
myphmcy = {myphmcy}
/>
</div>
<div className="col-md-1">
<div> </div>
</div>
</div>
)
}
the child file:
const initialFieldValues ={
orderID:0,
date_time:'',
status:'',
status2:'',
pharmacyName:'',
customerName:'',
patientName:'',
patientAge:'',
address:'',
email:'',
teleNo:'',
customer_id:1,
pharmacy_id:0,//data obtaind from the URL have to posted as the pharmacyID when posting.
image:'',
imageSource:'',
imageData: null
}
export default function Upload(props) {
const {addOrEdit} = props
const {myphmcy} = props
console.log(myphmcy);
const [values, setValues] = useState(initialFieldValues)
const[errors, setErrors] = useState({})
const handleInputChange= e => {
const {name, value} = e.target;
setValues({
...values,
[name]:value
})
}
/*const addOrEdit = (formData, onSuccess) => {
ordersAPI().create(formData)
.then(res => {
onSuccess();
})
.catch(err => console.log(err.response.data))
}*/
const showPreview = e => {
if(e.target.files && e.target.files[0]){
let imageData = e.target.files[0];
const reader = new FileReader();
reader.onload = x => {
setValues({
...values,
imageData,
imageSource : x.target.result
})
}
reader.readAsDataURL(imageData)
}
else{
setValues({
...values,
imageData:null,
imageSource:''
})
}
}
const validate = () => {
let temp = {}
temp.customerName = values.customerName == "" ? false : true;
setErrors(temp)
return Object.values(temp).every(x => x == true)
}
const resetForm = () => {
setValues(initialFieldValues)
document.getElementById('image-uploader').value = null;
}
const handleFormSubmit = e => {
e.preventDefault()
if (validate()){
const formData = new FormData()
formData.append('orderID',values.orderID)
formData.append('date_time',values.date_time)
formData.append('status',values.status)
formData.append('status2',values.status2)
formData.append('pharmacyName',values.pharmacyName)
formData.append('customerName',values.customerName)
formData.append('patientName',values.patientName)
formData.append('patientAge',values.patientAge)
formData.append('address',values.address)
formData.append('email',values.email)
formData.append('teleNo',values.teleNo)
formData.append('customer_id',values.customer_id)
formData.append('pharmacy_id',myphmcy)
formData.append('image',values.image)
formData.append('imageData',values.ImageData)
addOrEdit(formData, resetForm)
alert("Your file is being uploaded!")
}
}
const applyErrorClass = field => ((field in errors && errors[field] == false) ? ' invalid-field' : '')
return (
<>
<div className="container text-center ">
<p className="lead"></p>
</div>
<form autoComplete="off" noValidate onSubmit={handleFormSubmit}>
<div className="card">
<div className="card-header text-center">Place Your Order Here</div>
<img src={values.imageSource} className="card-img-top"/>
<div className="card-body">
<div className="form-group">
<input type="file" accept="image/*" className="form-control-file" onChange={showPreview} id="image-uploader"/>
</div>
<div className="form-group">
<input type="datetime-local" className="form-control" placeholder="Date Time" name="date_time" value={values.date_time}
onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Enter the prescription items and qty" name="status" value={values.status} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="What are the symptoms?" name="status2" value={values.status2} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Pharmacy Name" name="pharmacyName" value={values.pharmacyName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className={"form-control" + applyErrorClass('customerName')} placeholder="Your Name" name="customerName" value={values.customerName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Patient Name" name="patientName" value={values.patientName} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Patient Age" name="patientAge" value={values.patientAge} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Delivery address" name="address" value={values.address} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Your Email" name="email" value={values.email} onChange={ handleInputChange}/>
</div>
<div className="form-group">
<input className="form-control" placeholder="Contact Number" name="teleNo" value={values.teleNo} onChange={ handleInputChange}/>
</div>
<div className="form-group text-center">
<button type="submit" className="btn btn-light">submit</button>
</div>
</div>
</div>
</form>
</>
)
}
The codes are so long. but I have uploaded them all for a better understanding of my issue.

Clear Form Fields in React on Submit

I know this has probably been asked a few times, but I simply cannot figure out how to clear the form fields after submission of the form. It is working perfectly, but all of the data remains in the fields once I submit. I have tried the resetForm but that doesn't seem to be working for me.
Any help is greatly appreciated!
import React from "react";
import axios from "axios";
import '../ticket.min.css'
import Form from 'react-bootstrap/Form'
import Col from 'react-bootstrap/Col'
import Button from 'react-bootstrap/Button'
class Ticket extends React.Component {
state = {
firstName: "",
lastName: "",
email: "",
content: "",
category: "",
urgency: "",
tickets: [],
}
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
};
handleSubmit = (event) => {
event.preventDefault();
this.setState({
firstName: '',
lastName: '',
email: '',
content: '',
category: '',
urgency: '',
})
};
addTicket = () => {
let url = "http://localhost:8080/tickets";
axios.post(url, {
firstName: this.state.firstName,
lastName: this.state.lastName,
email: this.state.email,
content: this.state.content,
category: this.state.category,
urgency: this.state.selectedOption
}).then(response => {
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 onSubmit={this.handleSubmit}>
<label>First Name:</label>
<input type="text" name="firstName" value={this.state.firstName} onChange={this.handleChange} />
<br></br>
<label>Last Name:</label>
<input type="text" name="lastName" value={this.state.lastName} onChange={this.handleChange} />
<br></br>
<label>Email:</label>
<input type="text" name="email" value={this.state.email} onChange={this.handleChange} />
<br></br>
<label>
Select a Category:<br></br>
<select value={this.state.category} onChange={(e) => this.setState({ category: e.target.value })}>
<option value="hardware">Hardware</option>
<option value="software">Software</option>
<option value="internet">Internet</option>
<option value="other">Other</option>
</select>
</label>
<label>Please Describe Your Issue:</label>
<br></br>
<textarea value={this.state.content} name="content" onChange={this.handleChange} />
<label>
Select the Urgency Level:<br></br>
<input
type="radio"
name="selectedOption"
value="Urgent"
checked={this.state.selectedOption === "Urgent"}
onChange={this.handleChange}
/>
Urgent<br></br>
<input
type="radio"
name="selectedOption"
value="Normal"
checked={this.state.selectedOption === "Normal"}
onChange={this.handleChange}
/>
Normal<br></br>
<input
type="radio"
name="selectedOption"
value="Low Priority"
checked={this.state.selectedOption === "Low Priority"}
onChange={this.handleChange}
/>
Low Priority
</label>
<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}>
<b>First Name:</b>{p.firstName} <b>Last Name:</b>{p.lastName} <b>Email:</b>{p.email} <b>Issue:</b>{p.content} <b>Category:</b>{p.category} <b>Urgency:</b>{p.urgency}
</li>
))}
</ul>
</div>
);
}
}
export default Ticket;

where to put my header and footer tags in reactjs

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { login } from '../../redux/reducer';
import './LoginForm.css';
class LoginForm extends Component {
constructor(props) {
super(props);
this.state = {};
this.onSubmit = this.onSubmit.bind(this);
}
render() {
let {username, password} = this.state;
let {isLoginPending, isLoginSuccess, loginError} = this.props;
return (
<header>
<h1>Company Login</h1>
</header>
<form name="loginForm" onSubmit={this.onSubmit}>
<div className="form-group-collection">
<div className="form-group">
<label>Username/User ID:</label>
<input name="username" onChange={e => this.setState({username: e.target.value})} value={username}/>
</div>
<div className="form-group">
<label>Password:</label>
<input type="password" name="password" onChange={e => this.setState({password: e.target.value})} value={password}/>
</div>
</div>
<br/>
<input type="submit" value="Login" />
</form>
<footer>Copyright © multihands.com. </footer>
)
}
onSubmit(e) {
e.preventDefault();
let { username, password } = this.state;
this.props.login(username, password);
this.setState({
username: '',
password: ''
});
}
}
const mapStateToProps = (state) => {
return {
isLoginPending: state.isLoginPending,
isLoginSuccess: state.isLoginSuccess,
loginError: state.loginError
};
}
const mapDispatchToProps = (dispatch) => {
return {
login: (username, password) => dispatch(login(username, password))
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);
This is my login page i want to add header in my page.. I added it already as shown in the code...But unfortunetly error occurs after running.. Where does I put my header and footer tag in my code.. If we put it in form the code runs..But the css applied to the form is affected by adding the footer and header.. So I need the correct way to place header and footer without intrude my form..
Issue is that return statement must contain a single element only and your code contains three. So basically this should work:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { login } from '../../redux/reducer';
import './LoginForm.css';
class LoginForm extends Component {
constructor(props) {
super(props);
this.state = {};
this.onSubmit = this.onSubmit.bind(this);
}
render() {
let { username, password } = this.state;
let { isLoginPending, isLoginSuccess, loginError } = this.props;
return (
<div>
<header>
<h1>Company Login</h1>
</header>
<form name="loginForm" onSubmit={this.onSubmit}>
<div className="form-group-collection">
<div className="form-group">
<label>Username/User ID:</label>
<input name="username" onChange={e => this.setState({ username: e.target.value })} value={username} />
</div>
<div className="form-group">
<label>Password:</label>
<input type="password" name="password" onChange={e => this.setState({ password: e.target.value })} value={password} />
</div>
</div>
<br />
<input type="submit" value="Login" />
</form>
<footer>Copyright © multihands.com. </footer>
</div>
)
}
onSubmit(e) {
e.preventDefault();
let { username, password } = this.state;
this.props.login(username, password);
this.setState({
username: '',
password: ''
});
}
}
const mapStateToProps = (state) => {
return {
isLoginPending: state.isLoginPending,
isLoginSuccess: state.isLoginSuccess,
loginError: state.loginError
};
}
const mapDispatchToProps = (dispatch) => {
return {
login: (username, password) => dispatch(login(username, password))
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);
You need a wrapper inside your render function this solution should reolve your issue:-
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { login } from '../../redux/reducer';
import './LoginForm.css';
class LoginForm extends Component {
constructor(props) {
super(props);
this.state = {};
this.onSubmit = this.onSubmit.bind(this);
}
render() {
let { username, password } = this.state;
let { isLoginPending, isLoginSuccess, loginError } = this.props;
return (
<div className="wrapper">
<header>
<h1>Company Login</h1>
</header>
<form name="loginForm" onSubmit={this.onSubmit}>
<div className="form-group-collection">
<div className="form-group">
<label>Username/User ID:</label>
<input name="username" onChange={e => this.setState({ username: e.target.value })} value={username} />
</div>
<div className="form-group">
<label>Password:</label>
<input type="password" name="password" onChange={e => this.setState({ password: e.target.value })} value={password} />
</div>
</div>
<br />
<input type="submit" value="Login" />
</form>
<footer>Copyright © multihands.com. </footer>
</div>
);
onSubmit(e) {
e.preventDefault();
let { username, password } = this.state;
this.props.login(username, password);
this.setState({
username: '',
password: ''
});
}
}
}
const mapStateToProps = (state) => {
return {
isLoginPending: state.isLoginPending,
isLoginSuccess: state.isLoginSuccess,
loginError: state.loginError
};
}
const mapDispatchToProps = (dispatch) => {
return {
login: (username, password) => dispatch(login(username, password))
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginForm);
If you don't need the wrapper div you can use the Fragments(https://reactjs.org/docs/fragments.html) if using React Fiber.
<React.Fragment>
<header>
<h1>Company Login</h1>
</header>
<form name="loginForm" onSubmit={this.onSubmit}>
<div className="form-group-collection">
<div className="form-group">
<label>Username/User ID:</label>
<input name="username" onChange={e => this.setState({ username: e.target.value })} value={username} />
</div>
<div className="form-group">
<label>Password:</label>
<input type="password" name="password" onChange={e => this.setState({ password: e.target.value })} value={password} />
</div>
</div>
<br />
<input type="submit" value="Login" />
</form>
<footer>Copyright © multihands.com. </footer>
</React.Fragment>

Categories

Resources