React Onclick button change forms - node.js

I need help to change the pages of my app.
I searched a lot but still don't know how to do that.
Here is my index file:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
Here is my App file:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Login from "./Login";
class App extends Component {
render() {
return (
<div className="App">
<Login />
</div>
);
}
}
export default App;
Here is my Login file:
import React from 'react';
import CreateUser from "./CreateUser";
export default class Login extends React.Component {
state = {
email: '',
password: '',
};
change = e => {
this.setState({
[e.target.name]: e.target.value
});
};
onSubmit = (e) => {
e.preventDefault();
console.log(this.state);
};
render() {
return (
<form>
<br />
Login
<br />
<br />
<input
name="email"
placeholder='email'
value={this.state.email}
onChange={e => this.change(e)}
/>
<br />
<br />
<input
name="password"
type='password'
placeholder='password'
value={this.state.password}
onChange={e => this.change(e)}
/>
<br/>
<br/>
<button onClick={e => this.onSubmit(e)}>Login</button>
<br/>
<br/>
<button onClick={e => this.onSubmit(e)}>Sign Up</button>
</form>
);
}
}
Here is my Create user file:
import React from 'react';
export default class CreateUser extends React.Component {
state = {
email: '',
FirstName: '',
LastName: '',
personalphone: '',
password: '',
retypepassword: '',
};
change = e => {
this.setState({
[e.target.name]: e.target.value
});
};
onSubmit = (e) => {
e.preventDefault();
console.log(this.state);
};
render() {
return (
<form>
<br />
Create User
<br />
<br />
<input
name="email"
placeholder='email'
value={this.state.email}
onChange={e => this.change(e)}
/>
<br />
<br />
<input
name="FirstName"
placeholder='FirstName'
value={this.state.FirstName}
onChange={e => this.change(e)}
/>
<br />
<br />
<input
name="LastName"
placeholder='LastName'
value={this.state.LastName}
onChange={e => this.change(e)}
/>
<br />
<br />
<input
name="personalphone"
placeholder='personalphone'
value={this.state.personalphone}
onChange={e => this.change(e)}
/>
<br />
<br />
<input
name="retypepassword"
type='retypepassword'
placeholder='retypepassword'
value={this.state.retypepassword}
onChange={e => this.change(e)}
/>
<br />
<br />
<input
name="password"
type='password'
placeholder='password'
value={this.state.password}
onChange={e => this.change(e)}
/>
<br/ >
<br/ >
<button onClick={e => this.onSubmit(e)}>Submit</button>
</form>
);
}
}
I want to change the page of login to createuser when I click the button Sign Up.
Thx a lot,
Eduardo Gris

You could just keep state of which screen it should show.
Quick example which you can make a lot nicer
constructor() {
super()
this.state = {
screen: 'login'
}
}
handleButtonClick(page) {
this.setState({ screen: page })
}
render() {
return(
<div>
{
this.state.screen === 'login' ?
<Login />
:
<SignUp />
}
<button onClick={(e) => this.handleButtonClick(e.target.value)} value='signup' />
</div>
)
}

Related

how to FETCH POST data from REACT FORM to MongoDB

i want tp Fetch POST data into mongodb cluster from a REACT FORM ,
how to extract value of inputs by name and get them into the post method ?
because i used req.body.NAME ... but it does not work
class Formulaire extends Component {
constructor(props) {
super(props)
}
addProduct = () => {
fetch('http://localhost:2904/addproduct' , {
method : 'POST',
body : JSON.stringify({
image :req.body.image ,
name :req.body.name,
price : req.body.price
}),
headers : {
'Content-type' : 'application/json'
}
})
}
render() {
return (
<div className = "formualire">
<form onSubmit = {this.addProduct}>
<input type="text" name="image" /> <br/>
<input type="text" name="name" /> <br/>
<input type="number" name="price" /> <br/>
<button type="submit">Post</button>
</form>
</div>
);
}
}
import React from 'react'
import { useForm } from "react-hook-form";
import { withRouter } from 'react-router-dom';
function Formulaire(props) {
const { register, handleSubmit } = useForm();
const addProduct = (data) => {
fetch('http://localhost:2904/addproduct', {
method: 'POST',
body: JSON.stringify({
image: data.image,
name: data.name,
price: parseInt(data.price)
}),
headers: {
'Content-type': 'application/json'
}
})
}
const aa =(data) => {
console.log(parseInt(data.price))
}
return (
<div className="formualire">
<form onSubmit={handleSubmit(addProduct)}>
<input type="text" {...register('image', { required: true })} /> <br />
<input type="text" {...register('name', { required: true })} /> <br />
<input type="number" {...register('price', { required: true })} /> <br />
<input type="submit" />
</form>
</div>
);
}
export default Formulaire;

React - history.push not working after data fetch

I have some code coming back from my database and i want to redirect in the .then - when and if there is a res , but when i put the history.push in the .then- it doesn't render anything of inside the .then
here is some code:
import React, { useState } from 'react'
import { connect } from "react-redux";
import { CreateAccount as createAccountService } from '../services/user'
import { actions } from '../store/actions';
import { Redirect, withRouter } from "react-router-dom";
import { useHistory } from 'react-router-dom';
const mapStateToProps = (state) => {
return { ...state, user: state.userReducer.user || [] }
}
const mapDispatchToProps = (dispatch) => ({
setUser: (loggedUser) => dispatch(actions.setUser(loggedUser))
})
const CreateAccount = withRouter(function CreateAccount(props) {
const history = useHistory();
const [nameI, setName] = useState('');
const [emailI, setEmail] = useState('');
const [passwordI, setPassword] = useState('');
function createAccountHandler() {
createAccountService({ name: nameI, email: emailI, password: passwordI })
.then(res => {
alert(res.name) //brings the res.name but when the history.push is here it doens't show the alert
history.push('/posts') // <= the problem!
})
.catch((err) => {
alert('err in createAccount' + err)
})
}
return (<>
<div className="wrapper fadeInDown">
<div id="formContent">
<form>
<input type="text" id="name" class="fadeIn first" name="name" placeholder="name" onChange={e => setName(e.target.value)} />
<input type="text" id="email" class="fadeIn second" name="email" placeholder="email" onChange={e => setEmail(e.target.value)} />
<input type="text" id="password" class="fadeIn third" name="createAccount" placeholder="password" onChange={e => setPassword(e.target.value)} />
<input onClick={createAccountHandler} type="submit" class="fadeIn fourth" value="Create Account" />
</form>
</div>
</div>
</>)
}
)
export default connect(
mapStateToProps,
mapDispatchToProps
)(CreateAccount);
You Should try the following:
<form onSubmit={createAccountHandler}>
<input type="text" id="name" class="fadeIn first" name="name" placeholder="name" onChange={e => setName(e.target.value)} />
<input type="text" id="email" class="fadeIn second" name="email" placeholder="email" onChange={e => setEmail(e.target.value)} />
<input type="text" id="password" class="fadeIn third" name="createAccount" placeholder="password" onChange={e => setPassword(e.target.value)} />
<input type="submit" class="fadeIn fourth" value="Create Account" />
</form>
const createAccountHandler = (e) => {
e. preventDefault();
createAccountService({ name: nameI, email: emailI, password: passwordI })
.then(res => {
alert(res.name) //brings the res.name but when the history.push is here it doens't show the alert
history.push('/posts') // <= the problem!
})
.catch((err) => {
alert('err in createAccount' + err)
});
}

Proxy error: Could not proxy request /send from localhost:3000 to http://localhost:3001/

I'm sending some data from my ReactJS front-end application to my node/express backend, however, whenever I send the data, I get the error message mentioned in the title.
https://ibb.co/KbpwqZv
contact.js
This is my react js code where i declare my react from those who communicate with backend via axios
import React, { useState } from 'react'
import "./Contact.css";
import Axios from 'axios';
import {API} from '../backend';
const Contact = () => {
const [state,setState]= useState({
name:'',
lastname:'',
email:'',
message:'',
})
const [result,setResult] = useState(null);
const sendMail = e =>{
e.preventDefault();
Axios.post('/send',{...state})
.then(response => {
setResult(response.data);
setState({
name:'',
lastname:'',
email:'',
message:''
})
})
.catch(()=>{
setResult({
success:false,
message:"Something went wrong. Try again later"
})
setState("");
})
}
const onInputChange = e =>{
const {name,value} = e.target;
setState({
...state,
[name]: value
})
}
console.log("API is",API);
return (
<>
{result && (
<p className={`${result.success ? 'success' : 'error'}`}>
{result.message}
</p>
)}
<section className='contactus'>
<div className="container">
<h1 className='title'>CONTACT US</h1>
<form >
<div className="singleItem">
<label htmlFor="name">Name</label>
<input type="text"
name="name"
className="name"
placeholder="Your Name..."
value={state.name}
onChange={onInputChange}
/>
</div>
{/* <div className="singleItem">
<label htmlFor="Lastname">LastName</label>
<input type="text"
name="LastName"
className="LastName"
placeholder="Your Last Name..."
value={state.lastname}
onChange={onInputChange}
/>
</div> */}
<div className="singleItem">
<label htmlFor="email">Email</label>
<input type="email"
name="email"
className="email"
placeholder="Your Email..."
value={state.email}
onChange={onInputChange}
/>
</div>
<div className='textArea singleItem'>
<label htmlFor="message">Message</label>
<textarea name="message"
id=""
col="30"
rows="5"
placeholder="Your Message..."
value={state.message}
onChange={onInputChange}
>
</textarea>
</div>
<div className="msg">Message has been Sent</div>
<button type="button" className='btn btn-primary' onClick={sendMail}>Submit</button>
</form>
</div>
</section>
</>
)
}
export default Contact;

using React can I prevent sending empty strings from my inputs to my mongodb database during update?

I have inputs that take in information that is set to the state. The states initial values is set to empty strings. none of the inputs are required inputs so some may remain blank I then send the inputted information to the the API but that may send possible empty strings which would replaces information that I don't want to update.
I tried setting the initial states to undefined but i got the uncontrolled inputs error because I know undefined values would not be accepted in my database.
I have thought about maybe creating an array and pushing only the values that aren't equal to an empty string into it and then sending the array to the API.
import React from "react";
import API from "../../utils/API";
import { Link } from "react-router-dom";
import { storage } from "../../config/fire";
class ProfileEditor extends React.Component {
state = {
image: null,
url: "",
isActive: false,
emailaddress: "",
password: "",
confirm: "",
screenName: "",
securityQuestion: "",
securityAnswer: "",
birthDate: "",
gender: "",
phoneNumber: "",
cityState: "",
userPic: "",
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
updateProfile = id => {
if (this.state.password.length > 0 && this.state.password.length < 6) {
alert(
`Choose a more secure password `
);
} else if (this.state.password !== this.state.confirm) {
alert("You Passwords do not match");
} else {
API.updateEditProfile(id, {
password: this.state.password,
screenName: this.state.screenName,
securityQuestion: this.state.securityQuestion,
securityAnswer: this.state.securityAnswer,
birthDate: this.state.birthDate,
gender: this.state.gender,
phoneNumber: this.state.phoneNumber,
cityState: this.state.cityState,
userPic: this.state.url
})
.then(function (response) {
console.log(response);
})
.catch(err => console.log(err));
document.getElementById("profileForm").reset();
}
}
handleImageSelected = event => {
this.uploadClick()
if (event.target.files[0]) {
const image = event.target.files[0];
this.setState(() => ({ image }));
}
}
handleUpload = () => {
const fullName = this.props.userInfo.firstname + "_" + this.props.userInfo.lastname;
const { image } = this.state;
const uploadTask = storage.ref(fullName + "/" + image.name).put(image);
uploadTask.on("state_changed",
(snapshot) => {
const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
this.setState({ progress: progress })
},
(error) => {
console.log(error);
},
() => {
storage.ref(fullName).child(image.name).getDownloadURL()
.then(url => {
this.setState({ url: url });
console.log(url)
})
});
}
uploadClick = () => {
this.setState({ isActive: !this.state.isActive })
};
render() {
const fullName = this.props.userInfo.firstname + " " + this.props.userInfo.lastname
const user = this.props.userInfo
console.log(this.props.userInfo.userPic)
return (
<div className="contentArea ">
<div className="profile-container">
<div className="profile-image">
<img src={this.props.userInfo.userPic} />
</div>
<div className="profile-info">
{fullName}
</div>
<section className="editProfile">
<div className="unchangeable">Name: {fullName} </div>
<div className="unchangeable">Email: {this.props.userInfo.emailaddress}</div>
<form id="profileForm">
<div className="profileInputs">
<input value={this.state.password} onChange={this.handleChange} type="password" placeholder="Password" name="password" ref="password" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.confirm} onChange={this.handleChange} type="password" placeholder="confirm password" name="confirm" ref="confirmPassword" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.securityQuestion} onChange={this.handleChange} type="text" placeholder="security question" name="securityQuestion" ref="securityQuestion" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.securityAnswer} onChange={this.handleChange} type="text" placeholder="Answer to security question" name="securityAnswer" ref="securityAnswer" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.screenName} onChange={this.handleChange} placeholder="screen name" name="screenName" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.birthDate} onChange={this.handleChange} type="text" placeholder="birth date" name="birthDate" className="editInput" />
</div>
<div className="profileInputs">
<input value={this.state.Gender} onChange={this.handleChange} type="text" placeholder="gender" name="gender" className=" editInput" />
</div>
<div className="profileInputs">
<input value={this.state.phoneNumber} onChange={this.handleChange} type="text" placeholder="phone number" name="phoneNumber" className=" editInput" />
</div>
<div className="profileInputs">
<input value={this.state.cityState} onChange={this.handleChange} type="text" placeholder="city/state" name="cityState" className=" editInput" />
</div>
<div className="profileInputs"> Are you in a Relationship?
<input value={this.state.Gender} onChange={this.handleChange} type="text" placeholder="" name="gender" className=" editInput" />
</div>
</form>
</section>
<section className="feed ">
<div className="avatar">
<div className="avatarsect">
Upload Avatar
</div>
<input type="file" style={{ display: "none" }} onChange={this.handleImageSelected} ref={fileInput => this.fileInput = fileInput} />
<img className={this.state.isActive ? "uploadReady active" : "uploadReady"} src={this.state.url} alt="previewupload" height="40" width="50" />
<progress className={this.state.isActive ? "uploadReady active" : "uploadReady"} value={this.state.progress} max="100" />
<button className={this.state.isActive ? "uploadReady active" : "uploadReady"} onClick={this.handleUpload}>Upload</button>
<span className={this.state.isActive ? "uploadReady active" : "uploadReady"}></span>
<button type="button" className="button photo" onClick={() => this.fileInput.click()}><i class="fas fa-camera-retro"></i></button>
</div>
<br></br>
<br></br>
<div className="btnDiv">
<button onClick={() => this.updateProfile(this.props.userInfo.user_ID)} className="updateProfileBtn"> Update Profile</button>
</div>
<br></br>
<br></br>
<br></br>
<br></br>
</section>
</div>
</div>
);
}
}
export default ProfileEditor;
my Api
updateEditProfile:function(id,userData) {
console.log(userData)
console.log(id)
return axios.put("/api/usersData/" +id, userData);
},
my route and controller
router.route("/")
.post(usersDataController.findUserinfo)
.put(usersDataController.update)
router.route("/:id")
.put(usersDataController.updateByID);
updateByID: function(req, res) {
console.log(res)
db.usersData
.findByIdAndUpdate({ _id: req.params.id }, req.body,{new:true})
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},

Using this.refs is deprecated error when trying to use this.refs.value

II am trying to do a post request to the database to post an object called questions using "react-dom": "^15.6.1". The data might be something as follows:
{description: 'What is E-commerce?', ismeeting: false, expID: '123A2'}
What i am trying to do is take the "description" , "ismeeting" and ,"expID" values from a form and a checkbox (checkbox for "ismeeting") in the front end and pass it to the backend. To get the description value for instance; i am using this.refs.description.value. However i am getting an error Using this.refs is deprecated in the onSubmit(e) function and Using string literals in ref attributes is deprecated react/no-string-refs in the render() function
Here is the OnSubmit code.
onSubmit(e) {
const newQues = {
description: this.refs.description.value,
ismeeting: this.refs.check_me.checked,
expID: this.refs.expID.value
};
this.addQues(newQues);
e.preventDefault();
}
and here is the render() code.
render() {
return (
<div>
<br/>
<h1> DO NOT HESISTATE TO ASK OUR EXPERTS </h1>
<form onSubmit={this.onSubmit.bind(this)}>
<div className="input-field">
<input type="text" name="description" ref="description"/>
<label htmlFor="description"> Description </label>
</div>
<div className="input-field">
<input type="text" name="expID" ref="expID"/>
<label htmlFor="name"> expID </label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" name="ismeeting" ref="check_me" />Meeting
</label>
</div>
<input type ="submit" value="ASK" className="btn" />
</form>
</div>
);
}
finally this is the full code.
import React, { Component } from 'react';
import axios from 'axios';
import '../Styles.scss';
class Questions extends Component {
addQues(newQues) {
console.log(newQues);
axios.request({
method: 'Post',
url: 'http://localhost:3001/api/Questions',
data: newQues
}).then(response => {
}).catch(err => console.log(err));
}
constructor() {
super();
this.state = {
Questions: []
};
}
onSubmit(e) {
const newQues = {
description: this.refs.description.value,
ismeeting: this.refs.check_me.checked,
expID: this.refs.expID.value
};
this.addQues(newQues);
e.preventDefault();
}
render() {
return (
<div>
<br/>
<h1> DO NOT HESISTATE TO ASK OUR EXPERTS </h1>
<form onSubmit={this.onSubmit.bind(this)}>
<div className="input-field">
<input type="text" name="description" ref="description"/>
<label htmlFor="description"> Description </label>
</div>
<div className="input-field">
<input type="text" name="expID" ref="expID"/>
<label htmlFor="name"> expID </label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" name="ismeeting" ref="check_me" />Meeting
</label>
</div>
<input type ="submit" value="ASK" className="btn" />
</form>
</div>
);
}
}
export default Questions;
String refs have been deprecated. So what you need to do is update your refs
<input type="text" name="expID" ref="expID"/>
should be updated to
setExpIdRef = (r) => this.expIdRef = r;
onSubmit = (e) => {
const newQues = {
expID: this.expIdRef.value
};
// Do what you need to with newQuest i.e call your database
}
render() {
...
<input type="text" name="expID" ref={this.setExpIdRef}/>
}
The best solution is to make your inputs controlled inputs. Where you keep track of the value in the state.
constructor() {
super();
this.state = {
expID: ''
};
}
onExpIdChange = (e) => {
this.setState({
expID: e.target.value
})
}
onSubmit = (e) => {
const newQues = {
expID: this.state.expID
};
// Do what you need with the newQues object
}
render() {
...
<input type="text" name="expID" onChange={this.onExpIdChange} />
}

Resources