how do I hide/display the submit button in React JS - reactjs

I am completely new to React JS, I have no Idea how to do in ReactJS.
I have to hide the Submit button initially, when keyin to dates fields then Submit button should be display.
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { startdate: '', enddate: '' };
}
mySubmitHandler = (event) => {
event.preventDefault();
alert("You are submitting " + this.state.startdate +"and"+ this.state.enddate);
}
myChangeHandler = (event) => {
this.setState({startdate: event.target.value});
}
myEndDate = (event) => {
this.setState({enddate: event.target.value});
}
render() {
return (
<form onSubmit={this.mySubmitHandler}>
<img src="C:\\Users\\A9002255\\Desktop\is.jpg"></img>
<h2>Please select the Date range of .CSV </h2>
<input
type='date'
onChange={this.myChangeHandler}
/>
<span> </span>
<input
type="date"
onChange={this.myEndDate}
/>
<div>
<input
type='submit' value="Download" class="bi bi-cloud-arrow-down" style={{ width: '10%', height: 30}}
/>
</div>
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
export default MyForm;

You can add check on base of start and end dates of your state.
Try following code
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { startdate: '', enddate: '' };
}
mySubmitHandler = (event) => {
event.preventDefault();
alert("You are submitting " + this.state.startdate +"and"+ this.state.enddate);
}
myChangeHandler = (event) => {
this.setState({startdate: event.target.value});
}
myEndDate = (event) => {
this.setState({enddate: event.target.value});
}
render() {
return (
<form onSubmit={this.mySubmitHandler}>
<img src="C:\\Users\\A9002255\\Desktop\is.jpg"></img>
<h2>Please select the Date range of .CSV </h2>
<input
type='date'
onChange={this.myChangeHandler}
/>
<span> </span>
<input
type="date"
onChange={this.myEndDate}
/>
<div>
{this.state.startdate && this.state.enddate && <input
type='submit' value="Download" class="bi bi-cloud-arrow-down" style={{ width: '10%', height: 30}}
/>}
</div>
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
export default MyForm;

Related

How do i display booking details on confirmation page using mern stack

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

multiinput from submission in react js

I am trying to submit a form in react js I have multiple files
this.state = {
allValues: [],
};
changeHandler = (e) => {
this.setState({ ...this.allValues, [e.target.name]: e.target.value });
};
onsubmbit = (e) => {
e.preventDefault();
console.log(this.state.allValues);
};
<form onSubmit={this.onsubmbit}>
<input type='text' name='bloodsugar' onChange={this.changeHandler} value='' />
<input
type='text'
name='bloodpressure'
onChange={this.changeHandler}
value=''
/>
<button type='submit' style={styles.subbtn}>
Submit
</button>
</form>;
I am trying to submit a form in react js I have multiple files
I am trying to submit this form
console.log(this.state.allValues); when i console log it in submit function i want data as
{
bloodsugar:data of bloodsugar,
bloodpressure:data of bloodsugar,
}
when I console log it in submit function I want data like this
You have to set the value of each input field from the state that you set with changeHandler method. Additionally, you need to update the changeHandler method to update the state.allValues as follows.
(Following is the example code I used to test locally. Do the necessary modifications to fit it to your implementation)
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
allValues: {
bloodsugar: "",
bloodpressure: "",
},
};
}
changeHandler = (e) => {
this.setState({
allValues: { ...this.state.allValues, [e.target.name]: e.target.value },
});
};
onsubmbit = (e) => {
e.preventDefault();
console.log(this.state.allValues);
};
render() {
return (
<form onSubmit={this.onsubmbit}>
<div>
<div style={{ fontSize: "4rem", padding: "15px" }}>
<i className="fa fa-level-up"></i>
</div>
<div style={{ padding: "10px" }}>
<strong>Enter your blood sugar level</strong>
<br />
<input
type="text"
name="bloodsugar"
onChange={this.changeHandler}
value={this.state.allValues.bloodsugar}
/>
</div>
</div>
<div>
<div style={{ fontSize: "4rem", padding: "15px" }}>
<i className="fa fa-area-chart"></i>
</div>
<div style={{ padding: "10px" }}>
<strong>Enter your blood pressure level</strong>
<br />
<input
type="text"
name="bloodpressure"
onChange={this.changeHandler}
value={this.state.allValues.bloodpressure}
/>
</div>
</div>
<button type="submit">Submit</button>
</form>
);
}
}

How Can I get first element from API array

I am learning React and API. Here I am fetching data from API.I am trying to do on click button one user should appear. Or on click of user name all other user info should appear. I want to display one element from API array.If click on button new user should show. How to get only one user or one user info. Botton I added input box which can shoe only one value. I am stuck here.
import React from 'react';
import './App.css';
class Home extends React.Component {
constructor(props) {
super(props)
this.state = {
items: [],
error: '',
email:'',
phone:'',
companyName:''
}
this.handleInputChange = this.handleInputChange.bind(this);
this.showUserEmail = this.showUserEmail.bind(this);
}
handleInputChange(event){
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSelectUserName = (event) => {
console.log(event.target.value);
const myUser = (event.target.value);
this.setState({ name: event.target.value });
const selectedUser= event.target.value;
}
showUserEmail=(e)=>{
console.log("you are clicking name" );
this.setState({
})
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((result) => {
console.log(result);
console.warn(result);
this.setState({ items: result });
});
}
render() {
const { items } = this.state
return (
<div>
<button className="btn"> Show new User</button>
<div className="new-user" onChange={event => this. handleSelectNewUser(event)}>
{this.state.items.map(items => (
<span key={items.name} value={items.name}>
{items.name} <p></p></span>))}
</div>
<p className="para-text"> Data from API</p>
<div className="user-info">
{
items.length ?
items.map(items => <div key ={ items.id }>
<div className="user-details"> {items.name} </div>
<div className="user-details">{items.phone}</div>
<div className="user-details">{items.company.name}</div>
<div className="user-details">{items.username}</div>
<div className="user-details">{items.email}</div>
<div className="user-details">{items.website}</div>
</div>) : null
}
</div>
<h2>Find User By Username</h2>
<div className="input-box">
<select onChange={event => this.handleSelectUserName(event)}>
{this.state.items.map(items => (
<option key={items.name} value={items.name}>
{items.username}
</option>
))}
</select>
{/* Auto select */}
<div className=" Show-User-Auto">
<div className="input-box">
<input type="text"
placeholder=" Auto Select"
required="required"
onChange={event => this.handleInputChange(event)}
value={this.state.name} />
</div>
</div>
</div>
</div>
);
}
}
export default Home;
You have to maintain a state which contains userId , then you can condition render it like below code
import React from "react";
class Users extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
error: "",
email: "",
phone: "",
companyName: "",
userId: "",
orgList: []
};
this.handleInputChange = this.handleInputChange.bind(this);
this.showUserEmail = this.showUserEmail.bind(this);
}
handleSetUserId = (userId) => {
if (userId === this.state.userId) {
this.setState({ userId: "" });
} else {
this.setState({ userId });
}
};
handleInputChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSelectUserName = (event) => {
console.log(event.target.value);
const myUserId = event.target.value;
if (myUserId) {
console.log(this.state.orgList, "this.state.orgList");
let selectedUser = this.state.orgList.filter((item) => {
return item.id == Number(myUserId);
});
console.log(selectedUser, "selectedUser");
this.setState({ items: selectedUser });
}
};
showUserEmail = (e) => {
console.log("you are clicking name");
this.setState({});
};
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((result) => {
console.log(result);
console.warn(result);
this.setState({ items: result, orgList: result });
});
}
handleFetchAllUsers=()=>{
this.setState({items:this.state.orgList})
}
render() {
const { items } = this.state;
return (
<div>
<button className="btn" onClick={()=>this.handleFetchAllUsers()}> Show All User</button>
<div
className="new-user"
onChange={(event) => this.handleSelectNewUser(event)}
>
{this.state.items.map((items) => (
<span key={items.name}>
<br />
<span onClick={() => this.handleSetUserId(items.id)}>
{items.name}
<br />
</span>
{items.id === this.state.userId && (
<p>
<br />
<div className="user-details">{items.phone}</div>
<div className="user-details">{items.company.name}</div>
<div className="user-details">{items.username}</div>
<div className="user-details">{items.email}</div>
<div className="user-details">{items.website}</div>
</p>
)}
</span>
))}
</div>
<p className="para-text"> Data from API</p>
<h2>Find User By Username</h2>
<div className="input-box">
<select onChange={(event) => this.handleSelectUserName(event)}>
{this.state.orgList.map((items) => (
<option key={items.name} value={items.id}>
{items.username}
</option>
))}
</select>
{/* Auto select */}
<div className=" Show-User-Auto">
<div className="input-box">
<input
type="text"
placeholder=" Auto Select"
required="required"
onChange={(event) => this.handleInputChange(event)}
value={this.state.name}
/>
</div>
</div>
</div>
</div>
);
}
}
export default Users;
I have implemented the same in codesandbox you can use for ref

React - Pass form data into a function

I am new to React and I have a dashboard to display all users. I created a new feature to add a new user on the dashboard. Currently there is only one field to fill out which is the email.
Dashboard.js
<form id="new-user-form">
<fieldset>
<label>
<p>Email</p>
<input type="email" name="new-user" id="new-user" required />
</label>
</fieldset>
<button
type="button"
form="new-user-form"
onClick={this.onFormSubmit}
>
Add
</button>
</form>
and the method onFormSubmit function
onFormSubmit(event) {
var new_email = document.getElementById("new-user").value;
var today =
new Date().getFullYear() +
"-" +
("0" + (new Date().getMonth() + 1)).slice(-2) +
"-" +
("0" + new Date().getDate()).slice(-2);
let new_users = {
email: new_email,
registration: today,
status: "disabled",
};
this.setState((prevState) => ({
users: [...prevState.users, new_users],
}));
What I currently have works but there is no data-validation, I can add a user with an empty form because the new_email variable is taking document.getElementById("new-user").value which can be empty and should rather be the form data.
If you wanna see my full code for dashboard.js
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
users: [
{
email: "pierre-alexandre#gmail.com",
registration: "2020-10-25",
status: "active",
},
{
email: "antoine373#gmail.com",
registration: "2018-10-22",
status: "active",
},
{
email: "sofia.leduc#gmail.com",
registration: "2020-01-03",
status: "disabled",
},
],
searchEmail: "",
};
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(event) {
var new_email = document.getElementById("new-user").value;
var today =
new Date().getFullYear() +
"-" +
("0" + (new Date().getMonth() + 1)).slice(-2) +
"-" +
("0" + new Date().getDate()).slice(-2);
let new_users = {
email: new_email,
registration: today,
status: "disabled",
};
this.setState((prevState) => ({
users: [...prevState.users, new_users],
}));
}
handleLogout = () => {
fire.auth().signOut();
};
handleInput = (e) => {
this.setState({ searchEmail: e.target.value });
};
render() {
let filteredUsers = this.state.users.filter((user) => {
return user.email
.toLowerCase()
.includes(this.state.searchEmail.toLowerCase());
});
return (
<div>
<h2>Welcome</h2>
<button onClick={this.handleLogout}>Logout</button>
<div className="users-dashboard-container">
<div className="users-dashboard">
<div className="top-navigation">
<div className="search-navigation">
<img
src={process.env.PUBLIC_URL + "images/search.png"}
alt="logo"
/>
<SearchBox handleInput={this.handleInput} />
</div>
<div className="add-user">
<a>Add user</a>
</div>
</div>
<div class="dashboard-content">
<table>
<tr>
<th>Email</th>
<th>Registration Date</th>
<th>Status</th>
<th>Other</th>
</tr>
<UserList filteredUsers={filteredUsers} />
</table>
</div>
</div>
</div>
<div>
<div className="wrapper">
<h1>Add a User</h1>
<form id="new-user-form">
<fieldset>
<label>
<p>Email</p>
<input type="email" name="new-user" id="new-user" required />
</label>
</fieldset>
<button
type="button"
form="new-user-form"
onClick={this.onFormSubmit}
>
Add
</button>
</form>
</div>
</div>
</div>
);
}
}
export default Dashboard;
You can try like below.
handleChange = e => { // You can use this function to handle all inputs with name as state property
this.setState({ [e.target.name]: e.target.value }) // name will be `email`
}
formSubmit = () => {
if (!this.state.email) {
// Do email validations here
alert('Enter Email')
return
}
const today =
new Date().getFullYear() +
"-" +
("0" + (new Date().getMonth() + 1)).slice(-2) +
"-" +
("0" + new Date().getDate()).slice(-2);
const email = this.state.email
const new_user = {
email,
registration: today,
status: "disabled",
};
this.setState((prevState) => ({
users: [...prevState.users, new_user],
email: '' // Resets email once added into dashboard
}));
}
<div className="wrapper">
<h1>Add a User</h1>
<label>
<p>Email</p>(
<input
type="email"
name="email" // <- this will be used add state key
value={email}
onChange={handleChange} />
</label>
<button onClick={this.onFormSubmit}>
Add
</button>
</div>
One simple way is to disable the submit button if state.searchEmail is empty.
import React, { Component } from "react";
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
searchEmail: ""
};
this.onFormSubmit = this.onFormSubmit.bind(this);
this.handleInput = this.handleInput.bind(this);
}
onFormSubmit() {
let new_user = {
email: this.state.searchEmail
};
console.log(new_user);
}
handleInput(e) {
this.setState({ searchEmail: e.target.value });
};
render() {
return (
<form>
<label>
Email
<input
onChange={this.handleInput}
value={this.state.searchEmail}
type="email"
required
/>
</label>
<button
onClick={this.onFormSubmit}
disabled={this.state.searchEmail === ""}
>
Add
</button>
</form>
);
}
}
export default Dashboard;
You could take this approach further and move the validation into a function where you check state.searchEmail against a regex.
import React, { Component } from "react";
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
searchEmail: ""
};
}
onFormSubmit = (e) => {
e.preventDefault();
let new_user = {
email: this.state.searchEmail
};
console.log(new_user);
this.setState({ searchEmail: "" });
};
handleInput = (e) => {
this.setState({ searchEmail: e.target.value });
};
formIsInvalid = () => {
return (
this.state.searchEmail === "" ||
!this.state.searchEmail.match(/^[\w-.]+#([\w-]+\.)+[\w-]{2,4}$/)
);
};
render() {
return (
<form action="" onSubmit={this.onFormSubmit}>
<label>
Email
<input
onChange={this.handleInput}
value={this.state.searchEmail}
type="email"
required
/>
</label>
<button disabled={this.formIsInvalid()}>Add</button>
</form>
);
}
}
export default Dashboard;

Event / callback for when a user logs in with Meteor + React?

Im using Meteor and React. I need to redirect a user when they log in. Is there an event or callback for this?
import React from 'react';
import { Link, Redirect } from 'react-router-dom';
import './LogInPage.less';
class LogIn extends React.Component {
constructor(props) {
super(props);
this.state = {
error: false,
loggedIn: Meteor.userId() ? true : false,
};
this.login = this.login.bind(this);
}
login = e => {
e.preventDefault();
Meteor.loginWithPassword(this.email.value, this.password.value, err => {
if (err) {
this.setState({ error: err.reason });
}
});
// if (Meteor.userId()) this.setState({ loggedIn: true });
};
render() {
// if (Meteor.userId()) return <Redirect to="/" />;
return (
<div className="LogIn">
<form onSubmit={this.login}>
<label>Email</label>
<input type="email" ref={input => (this.email =
<label>Password</label>
<input type="password" ref={input => (this.password = input)} />
<button className="btn" type="submit">
Log in
</button>
{this.state.error && (
<p className="form-std__msg form-std__msg--err">
{this.state.error}
</p>
)}
</form>
</div>
);
}
}
export default LogInPage;
If no error then you can check using Meteor.user()
import React from 'react';
import { Link, Redirect } from 'react-router-dom';
import './LogInPage.less';
class LogIn extends React.Component {
constructor(props) {
super(props);
this.state = {
error: false,
loggedIn: Meteor.userId() ? true : false,
};
this.login = this.login.bind(this);
}
login = e => {
e.preventDefault();
Meteor.loginWithPassword(this.email.value, this.password.value, err => {
if (err) {
this.setState({ error: err.reason });
} else {
this.setState({ loggedIn: Meteor.user() ? true : false })
}
});
// if (Meteor.userId()) this.setState({ loggedIn: true });
};
render() {
if (this.state.loggedIn) return <Redirect to="/" />;
return (
<div className="LogIn">
<form onSubmit={this.login}>
<label>Email</label>
<input type="email" ref={input => (this.email = input)} />
<label>Password</label>
<input type="password" ref={input => (this.password = input)} />
<button className="btn" type="submit">
Log in
</button>
{this.state.error && (
<p className="form-std__msg form-std__msg--err">
{this.state.error}
</p>
)}
</form>
</div>
);
}
}
export default LogInPage;

Resources