I am a beginner in programming. I am building an appointment booking system using mern stack. I have created the booking form which sends data to the database, now i need to display the booking details ona confirmation page,which i am finding difficult. please this is where i need some help
import React, { Component } from 'react';
import axios from 'axios';
import DatePicker from 'react-datepicker'
import 'react-datepicker/dist/react-datepicker.css'
import { Link } from 'react-router-dom';
class Form extends Component {
constructor() {
super();
this.handleChange = this.handleChange.bind(this);
this.handleDateChange = this.handleDateChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this);
}
state = {
name: "",
service: "finance",
date: new Date(),
cost: "3"
};
styles = {
fontSize: 50,
fontWeight: "bold",
color: "blue"
}
//event to handle all inputs except datepicker
handleChange(e) {
const name = e.target.name;
const value = e.target.value;
//to update the input state
this.setState({ [name]: value });
}
//event to handle datepicker input
handleDateChange(date) {
//update the date state
this.setState({
date:date
})
}
handleSubmit(e) {
e.preventDefault()
//console.log(this.state);
if(this.state.value !== ""){
alert('booking success')
}
axios.post('http://localhost:5000/api', this.state)
.then(res => {
console.log(res)
})
.catch((error) => {
console.log(error)
})
this.setState({ name: '', service: '', date: '', cost: '' })
}
render() {
return (
<form className='form' onSubmit={this.handleSubmit}>
<h2 style={this.styles}>Create appointment</h2>
<div className="mb-3">
<label className="form-label">Name</label>
<input name='name' type="text" className="form-control" id="exampleFormControlInput1" value={this.state.name} onChange={this.handleChange} />
<label className="form-label">Service</label>
<input name='service' type="text" className="form-control " id="exampleFormControlInput1" value={this.state.service} onChange={this.handleChange} />
<label className="form-label"> Date</label>
<div>
<DatePicker
selected={this.state.date}
onChange={this.handleDateChange}
name='date'
/>
</div>
{/* <label className="form-label"> Date</label>
<input name='date'type="datetime-local" className="form-control" id="exampleFormControlInput1" value={this.state.date} onChange={this.handleChange} />
*/}
<label className="form-label">Cost</label>
<input name='cost' type="text" className="form-control" id="exampleFormControlInput1" value={this.state.cost} onChange={this.handleChange} />
</div>
<Link to={'/ConfirmBooking'} style={{ textDecoration: 'none' }}>
<input type="submit" value="Submit" className="btn btn-outline-success" />
</Link>
</form>
)
}
}
export default Form;
import React, { Component } from 'react';
import axios from 'axios';
import Form from './Form';
class ConfirmBooking extends Component {
constructor(props){
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
state = {
};
handleSubmit(e){
e.preventDefault();
axios.get('http://localhost:5000/api', this.state)
.then(res => {
console.log(res)
})
.catch((error) => {
console.log(error)
})
this.setState({ name: '', service: '', date: '', cost: '' })
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit} >
<h3>Booking review</h3>
</form >
</div>
);
}
}
export default ConfirmBooking
;
the first code is for the oking form which works fine. The one underneath is for displaying booking details but doesnt work. please kindly help me
Related
Hello I just want to make a form and my textboxes does not take my inputs and my submit works but sends no values. What am I doing wrong? I know it's a basic question but I don't know what the problem is in my code.
Key problems:
it doesn't update the state nor take my inputs.
fields editable but cant write into them
Code
import React, { Component } from "react";
class Postform extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
category: "",
price: "",
};
}
changeHandler = (e) => {
this.setState = { [e.target.name]: e.target.value };
};
submitHandler = (e) => {
e.preventDefault();
console.log(this.state);
};
render() {
const { name, category, price } = this.state;
return (
<div>
<form onSubmit={this.submitHandler}>
<div>
<input
type="text"
name="name"
placeholder="Name"
value={name}
onChange={this.changeHandler}
/>
<input
type="text"
name="category"
placeholder="Category"
value={category}
onChange={this.changeHandler}
/>
<input
type="text"
name="price"
placeholder="Price"
value={price}
onChange={this.changeHandler}
/>
</div>
<button type="submit">Add product</button>
</form>
</div>
);
}
}
export default Postform;
Change this line to
changeHandler = e => {
this.setState({[e.target.name]: e.target.value });
};
Since setState is a function it is not a property !
I have a form with a 'title' and a 'content'. The content is in the ReactQuill component which enables you to have rich text. Before adding that component, my 'onChange' was working fine for both 'inputs'. Now that the components are different it no longer works.
I get the error below:
this is the code in AddArticle.js which is where the form is:
import React, { Component } from "react";
import firebase from "../Firebase";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import renderHTML from "react-render-html";
class AddArticle extends Component {
constructor() {
super();
this.ref = firebase.firestore().collection("articles");
this.state = {
title: "",
content: "",
};
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
onSubmit = (e) => {
e.preventDefault();
const { title, content } = this.state;
this.ref
.add({
title,
content,
})
.then((docRef) => {
this.setState({
title: "",
content: "",
});
this.props.history.push("/");
})
.catch((error) => {
console.error("Error adding document: ", error);
});
};
render() {
return (
<div className="container">
<br></br>
<br></br>
<br></br>
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title text-center">Create a new article</h3>
</div>
<br></br>
<br></br>
<div className="panel-body">
<form onSubmit={this.onSubmit}>
<div className="form-group input-group-lg">
<label for="title">Title:</label>
<input
type="text"
className="form-control"
name="title"
value={this.state.title}
onChange={this.onChange}
placeholder="Title"
/>
</div>
<div className="form-group">
<label for="content">Content:</label>
<ReactQuill
theme="snow"
name="content"
value={this.state.content}
onChange={this.onChange}
placeholder="Content"
/>
</div>
<button type="submit" className="btn btn-success">
Submit
</button>
</form>
</div>
</div>
</div>
);
}
}
export default AddArticle;
The onChange for the title input receives an event containing name and value.
On the other hand the onChange for the Quill component receives the actual content.
All in all you should use:
onTitleChange = (e) => {
this.setState({ title: e.target.value });
};
onContentChange = (content) => {
this.setState({ content: content });
};
And pass these handlers approprietly to your title input and quill component.
I have a component that represents a form for entering book data, e.g. title/author/etc.
If an ID is present, the component will make an API call to the API server, and get the book data.
What I'm trying to accomplish basically, is getting the record from the API server, and then setting the form fields to those values, so that the form is populated with data for the user to edit.
I have a method called loadBook which makes an API call to get the book data. The method works, it gets the record, it sets the state, but the form inputs do not seem to pick up that the state has changed.
What do I need to do to get the form populated with the record that was just fetched?
import React from "react";
import Axios from "axios";
import {
Redirect
} from "react-router-dom";
import FormBase from "../FormBase";
export default class BookForm extends FormBase {
constructor(props) {
super(props);
this.state = {
formFields: {
title: '',
author_id: null,
cover_image: null
},
authors: [],
};
}
componentDidMount() {
this.loadAuthors();
if (this.props.id) {
this.loadBook()
}
}
loadBook = () => {
Axios.get(`${process.env.REACT_APP_API_URL}/books/${this.props.id}`).then(response => {
this.setState(prevState => {
let formFields = Object.assign({}, prevState.formFields)
formFields['title'] = response.data['title']
formFields['author_id'] = response.data['author_id']
return {formFields}
})
})
}
loadAuthors = () => {
Axios.get(`${process.env.REACT_APP_API_URL}/authors`).then(response => {
this.setState({authors: response.data})
})
}
render() {
let authors = this.state.authors.map(author => {
return <option key={author.id} value={author.id}>{author.last_name}, {author.first_name}</option>
})
return (
<form onSubmit={(e) => {e.preventDefault(); this.props.handleSubmit(e, this.state.formFields, true)}}>
{this.state.redirect ? <Redirect to="/admin/books" /> : null}
<div className="form-group">
<label htmlFor="title">Title</label>
<input name="title" value={this.state.title} onChange={this.handleFieldChange} type="text" className="form-control" />
</div>
<div className="form-group">
<label htmlFor="author">Author</label>
<select name="author_id" onChange={this.handleFieldChange} className="custom-select" size="5">
{authors}
</select>
</div>
<div className="custom-file form-group">
<input name="cover_image" type="file" onChange={this.handleFieldChange} className="custom-file-input" id="customFile" />
<label className="custom-file-label" htmlFor="customFile">Cover Image</label>
</div>
<button style={{marginTop: '1rem'}} type="submit" className="btn btn-primary">Submit</button>
</form>
)
}
}
Try setting your state simply like so:
this.setState({formFields:
{
...this.state.formFields,
title: response.data['title'],
author_id: response.data['author_id']
}
})
I essentially followed this guide on uncontrolled components.
I added attributes for each form field using React.createRef(), and then on the form inputs you link the ref object like ref={this.author_id}. Then, you can do this.author_id.current.value = response.data.author_id and the input's value will then be set. This won't trigger onChange though, so you'll need to update the state too.
import React from "react";
import Axios from "axios";
import {
Redirect
} from "react-router-dom";
import FormBase from "../FormBase";
export default class BookForm extends FormBase {
constructor(props) {
super(props);
this.state = {
formFields: {
title: '',
author_id: null,
cover_image: null
},
authors: [],
};
this.title = React.createRef();
this.author_id = React.createRef();
}
componentDidMount() {
this.loadAuthors();
if (this.props.id) {
this.loadBook()
}
}
loadBook = () => {
Axios.get(`${process.env.REACT_APP_API_URL}/books/${this.props.id}`).then(response => {
console.log(this.author_id)
this.author_id.current.value = response.data.author_id
this.title.current.value = response.data.title
this.setState(prevState => {
let formFields = Object.assign({}, prevState.formFields)
formFields['title'] = response.data['title']
formFields['author_id'] = response.data['author_id']
return {formFields}
})
})
}
loadAuthors = () => {
Axios.get(`${process.env.REACT_APP_API_URL}/authors`).then(response => {
this.setState({authors: response.data})
})
}
render() {
let authors = this.state.authors.map(author => {
return <option key={author.id} value={author.id}>{author.last_name}, {author.first_name}</option>
})
return (
<form onSubmit={(e) => {e.preventDefault(); this.props.handleSubmit(e, this.state.formFields, true)}}>
{this.state.redirect ? <Redirect to="/admin/books" /> : null}
<div className="form-group">
<label htmlFor="title">Title</label>
<input name="title" ref={this.title} value={this.state.title} onChange={this.handleFieldChange} type="text" className="form-control" />
</div>
<div className="form-group">
<label htmlFor="author">Author</label>
<select name="author_id" ref={this.author_id} onChange={this.handleFieldChange} className="custom-select" size="5">
{authors}
</select>
</div>
<div className="custom-file form-group">
<input name="cover_image" type="file" onChange={this.handleFieldChange} className="custom-file-input" id="customFile" />
I am trying to create a contact form in React. It sends the email. Everything is working fine. What I would like to achieve is to replace the alert('') with a better looking < Popup> message using react Popup package.
Here is the code:
import React, { Component } from 'react';
import '../css/Contact.css';
import axios from 'axios';
import Popup from "reactjs-popup";
class Contact extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
message: '',
isValid: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.validationCheck = this.validationCheck.bind(this);
}
handleChange = (event) => {
const name = event.target.id;
const value = event.target.value;
this.setState ({ [name] : value});
}
validationCheck () {
if((this.state.name.length)>3 &&
(this.state.message.length)>5 &&
(this.state.email.length)>7 &&
(this.state.email.includes("#")) &&
(this.state.email.includes(".")) &&
((this.state.name || this.state.message || this.state.message)!=0)
)
{
this.setState({ isValid: true});
this.forceUpdate();
};
}
async handleSubmit (event) {
this.validationCheck();
this.forceUpdate();
if ((this.state.isValid) === true) {
event.preventDefault();
const { name, email, message } = this.state;
const form = await axios.post('/api/form', {
name,
email,
message
});
alert('thank you for your message');
event.target.reset();
}
else {
event.preventDefault();
alert('you might have entered something wrong');
}
}
render() {
return (
<div className="contact">
<h1>Contact Me</h1>
<form id="form" onSubmit={this.handleSubmit}>
<div>
<label htmlFor="Name" className="badge badge-secondary">Name</label>
<input
onChange={this.handleChange} id="name" className="form-control" placeholder="Enter your name here."/>
</div>
<div>
<label htmlFor="Email" className="badge badge-secondary">Email address</label>
<input
onChange={this.handleChange}
id="email"
className="form-control"
placeholder="Enter your e-mail address here." />
</div>
<div className="">
<label htmlFor="Message" className="badge badge-secondary">Message</label>
<textarea
onChange={this.handleChange} rows="4"
className="form-control" id="message" placeholder="Enter your message here."></textarea>
</div>
<button
type="submit"
form="form"
className="btn btn-secondary btn-lg button"
id="submit"
value="Submit"> Send! </button>
</form>
<hr />
<button type="button" className="btn btn-outline-info" onClick={this.props.scrollToTop}>
Scroll me back to the top!</button>
</div>
);
}
}
export default Contact;
I have tried to replace 'alert('thank you for your message');' with return(< Popup>); but that is clearly not a way forward.
Here's a way how you can exactly use a reactjs-popup:
import React from "react";
import Popup from "reactjs-popup";
export default () => (
<Popup trigger={<button> Trigger</button>} position="right center">
<div>Popup content here !!</div>
</Popup>
);
All you need to do is put a trigger for it and it'll work
For help: https://react-popup.netlify.com/
I am on the beginning of my programming and that's my duty to code a forum web page with login. After login I am supposed to put come content and they should be editable but I am still on the beginning. I would be really happy if someone can help because right now I need to put the data into the database (I am able to get data drom the database I can consolo them)
It is really hard coding :(
But how to get the form to the database :/
This is tsx file on frontend side.
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
//import { Link, NavLink } from 'react-router-dom';
export class SignUp extends React.Component<RouteComponentProps<{}>, {}> {
constructor(props: RouteComponentProps<{}> | undefined) {
super(props);
this.state = {
name: '',
surname: '',
username: '',
email: '',
password: ''
};
this.handleNameChange = this.handleNameChange.bind(this);
this.handleSurnameChange = this.handleSurnameChange.bind(this);
}
handleNameChange(e: { preventDefault: () => void; target: { value: any; }; }) {
e.preventDefault();
this.setState({ name: e.target.value });
}
handleSurnameChange(e: { preventDefault: () => void; target: { value: any; }; }) {
e.preventDefault();
this.setState({ surname: e.target.value });
}
handleSubmit(e: any) {
e.preventDefault();
const formKayit = {
name: this.state.name,
surname: this.state.surname
};
console.log("uye oldunuz", formKayit);
}
public render() {
return (
<div>
<h1>We are glad to see you here. </h1>
<form >
<label>
Name:
<input className="form-control" type="text" onChange={(e) => { this.handleNameChange(name); }} //name="Name" value={this.state.Name} onChange={this.handleChange.bind(this)}
/>
</label>
<div>
<label>
Surname:
<input className="form-control" type="text" onChange={(e) => { this.handleSurnameChange(e); }} //name="Surname" value={this.state.Surname} onChange={this.handleChange.bind(this)}
/>
</label>
</div>
<div>
<label>
Username:
<input className="form-control" type="text" //name="Username" value={this.state.Username} onChange={this.handleChange.bind(this)}
/>
</label>
</div>
<div>
<label>
E-mail:
<input className="form-control" type="text" //name="Surname" value={this.state.Surname} onChange={this.handleChange.bind(this)}
/>
</label>
</div>
<label>
Password:
<input className="form-control" type="password" //name="Password" value={this.state.Password} onChange={this.handleChange.bind(this)}
/>
</label>
<div>
<button onClick={(e) => { this.handleSubmit(e); }} className="btn">SignUp </button>
</div>
</form>
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>