Render components based on state - javascript

I am working on a user registration/ log in page. I have two forms, a signUp form and a logIn form, and some state called signInState that determines which user form to display. I have two buttons that toggle the signInState, and if the signInState is true, I want it to display the log in form, if its false, I want to display the sign up form. The state is changing, but for some reason the conditional rendering is not working. Can someone help me figure out why my toggleSignInState doesn't change what's being rendered on the page? Thanks
Here is my react code for the signInPage itself
import React from 'react'
import SignUp from './SignUp'
import LogIn from './LogIn'
export default function SignInPage() {
const [signInState, setSignInState] = React.useState(true);
function toggleSignIn(event) {
console.log(event.target.id)
setSignInState(event.target.id);
/*setSignInState(event.target.value);*/
}
return (
<div className="signInPage">
<div className="signInPageFormContainer">
<p>{signInState}</p>
{!signInState && <SignUp /> }
{signInState && <LogIn /> }
<div className="signUpPageToggleContainer">
<button onClick={toggleSignIn} id='true'>Log In</button>
<button onClick={toggleSignIn} id='false'>Sign Up</button>
</div>
</div>
</div>
)
}
here is the code for the signUp form
import React from 'react'
export default function SignUp() {
return(
<form className="signUpForm">
<input
name="username"
type="text"
placeholder="Username"
className="signUpInput"
/>
<input
name="email"
type="text"
placeholder="Email"
className="signUpInput"
/>
<input
name="password"
type="text"
placeholder="Password"
className="signUpInput"
/>
<input
name="confirmPassword"
type="text"
placeholder="Confirm password"
className="signUpInput"
/>
<div>
<button>Sign Up</button>
<button>Cancel</button>
</div>
</form>
)
}
and here is the code for the log in form
import React from "react";
export default function LogIn() {
/*functions for log in procedure*/
return (
<form className="logInForm">
<input
placeholder="Username"
name="username"
type="text"
id="username"
className="logInFormInput"
/>
<input
placeholder="Password"
name="password"
type="text"
id="password"
className="logInFormInput"
/>
<div className="logInFormButtonContainer">
<button className="logInFormButton">Log In</button>
<button className="logInFormButton">Cancel</button>
</div>
</form>
)
}

Element attributes are strings. The string 'true' is not the same as the boolean true, and the string 'false' is not the same as the boolean false. Both 'true' and 'false' are truthy, so signInState is always truthy.
While you could perform string comparisons inside toggleSignIn to determine what to pass to the state setter, calling the state setter inline in the buttons would be easier.
<button onClick={() => { setSignInState(true); }}>Log In</button>
<button onClick={() => { setSignInState(false); }}>Sign Up</button>

Here the id from event object will always be Boolean true as they are not booleans they are strings, i.e., whatever you keep as value in a DOM attribute it would be a string in most of the cases and any string except empty string "" is true ...
The answer from CertainPerformance is better and easy to understand
In case you want to keep your code same and changing a little as below should work
function toggleSignIn(event) {
setSignInState(event.target.id === "true" ? true : false);
}

Related

Can't convert input element to re-usable component in react js

I created a login form and now I want to convert my input fields to re- usable component. I created separate common input.jsx file. This is input.jsx file's code.
import React from "react";
const Input = ({ name, label, value, onChange }) => {
return (
<div className="form-group">
<label htmlFor={name}>{label}</label>
<input
value={value}
onChange={onChange}
id={name}
name={name}
type="text"
className="form-control"
/>
</div>
);
};
export default Input;
and imported it to my loginForm.jsx. Here is my loginForm.jsx render method
handleChange = ({ currentTarget: input }) => {
const account = { ...this.state.account };
account[input.name] = input.value;
this.setState({ account });
};
render() {
const { account } = this.state;
return (
<div>
<h1>Login</h1>
<form onSubmit={this.handleSubmit}>
<Input
name="username"
value={account.username}
label="Username"
onChange={this.handleChange}
/>
<Input
name="password"
value={account.password}
label="Password"
onChange={this.handleChange}
/>
<button className="btn btn-primary">Login</button>
</form>
</div>
);
}
But after adding below code to my loginForm.jsx,
<Input
name="username"
value={account.username}
label="Username"
onChange={this.handleChange}
/>
code and deleted previous code ,
<div className="form-group">
<label htmlFor="username">Username</label>
<input
value={account.username}
name="username"
onChange={this.handleChange}
ref={this.username}
id="username"
type="text"
className="form-control"
/>
</div>
suddenly my login page not loading.(Empty page).
My login page's console showing below error.
The above error occurred in the <LoginForm> component:
at LoginForm (http://localhost:3000/main.5d4e82bfe117bc198b43.hot-update.js:27:5)
at Route (http://localhost:3000/static/js/bundle.js:54444:5)
at Switch (http://localhost:3000/static/js/bundle.js:54739:5)
at main
at App
at Router (http://localhost:3000/static/js/bundle.js:54612:5)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:53870:5)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

How can Prompt be used to stop navigation on formik dirty state

I'm using formik in a reactjs project, and I want to use Prompt from react-router to open a notification before a user leaves and loses changes made to their submission.
I'd expected something like this to work:
<Prompt
when={formik.dirty}
message="You have unsaved changes. Are you sure you want to leave?"
/>
My formik block looks like this:
const formik = useFormik({
initialValues: {
<values>
},
enableReinitialize: true,
validate,
onSubmit: values => {
<submit functional stuff>
}
});
And my form is something like this:
<form id="myForm" onSubmit={formik.handleSubmit}>
<div className="row">
<div className="form-group">
<label htmlFor="name">Name</label>
<input
id="name"
type="text"
onChange={formik.handleChange}
value={formik.values.name}
className="form-control"
placeholder="Enter name"
disabled={isDisabled}
/>
{formik.errors.name ? <div className="text-danger">{formik.errors.name}</div> : null}
</div>
<div className="form-group">
<label htmlFor="subject">Subject</label>
<input
id="subject"
type="text"
onChange={formik.handleChange}
value={formik.values.subject}
className="form-control"
placeholder="Email subject"
disabled={isDisabled}
/>
{formik.errors.subject ? <div className="text-danger">{formik.errors.subject}</div> : null}
</div>
</div>
</form>
but it appears that formik.dirty is either not defined or it's not seen as true (despite making changes to the form).
How would I properly use the dirty prop to trigger the Prompt?
I am not sure what kind of setup you have, but I created a PoC with routing which has two tabs (links) for navigation and I am using prompt on tab with formik form component.
import React from "react";
import { Prompt } from "react-router-dom";
import { useFormik } from "formik";
const MyForm = () => {
const formik = useFormik({
initialValues: {
name: "",
subject: ""
},
enableReinitialize: true,
onSubmit: (values) => {
alert(JSON.stringify(values, null, 2));
},
onChange: (e) => {
console.log(e);
}
});
return (
<div>
<Prompt
when={!!formik.dirty}
message={(location) =>
`Are you sure you want to go to ${location.pathname}`
}
/>
<form id="myForm" onSubmit={formik.handleSubmit}>
<div className="row">
<div className="form-group">
<label htmlFor="name">Name</label>
<input
id="name"
type="text"
onChange={formik.handleChange}
value={formik.values.name}
className="form-control"
placeholder="Enter name"
/>
{formik.errors.name ? (
<div className="text-danger">{formik.errors.name}</div>
) : null}
</div>
<div className="form-group">
<label htmlFor="subject">Subject</label>
<input
id="subject"
type="text"
onChange={formik.handleChange}
value={formik.values.subject}
className="form-control"
placeholder="Email subject"
/>
{formik.errors.subject ? (
<div className="text-danger">{formik.errors.subject}</div>
) : null}
</div>
{formik.dirty && <button tye="submit">Save</button>}
</div>
</form>
</div>
);
};
export default MyForm;
take a look the this codesandbox.

How to make use of Radio Group with useFormik Hook

I am trying to get useFormik to validate radio groups, but it seems not to work, here is a brief example of what I am doing, whenever I submit the form after checking any of the radio input, formik throws validation error, ({currState:"you must choose property state"}), even though I choose an option.
I realized getFieldProps attaches value field to the radio, so i tried using defaultValue then react throws an error about choosing one of controlled and uncontrolled components.
import { useFormik } from "formik"
export function ListProperty(){
const { handleSubmit, getFieldProps, touched, errors } = useFormik(
{
initialValues: {
currState:"",
},
validationSchema:Yup.object().shape({
currState:Yup.string().required("you must choose property state")
}),
return (
<form onSubmit={handleSubmit} >
<div className="form-group inline">
<div className="form-control">
<input type="radio"
name="currState"
{...getFieldProps("currState")}
value="serviced"
/>
<label>serviced</label>
</div>
<div className="form-control">
<input
type="radio"
value="furnished"
name="currState"
{...getFieldProps("currState")}
/>
<label>furnished</label>
</div>
<div className="form-control">
<input
type="radio"
value="newlybuilt"
name="currState"
{...getFieldProps("currState")}
/>
<label>newly built</label>
</div>
</div>
<button type="submit">submit </button>
</form>
)
}
I gave up on the implementation with getFieldProps and did it simpler, like this:
import { useFormik } from 'formik'
export default function Component() {
const formik = useFormik({
initialValues: {
radioButtonValue: ''
},
onSubmit: values => console.log(values)
})
const handleRadioButtons = e => formik.values.radioButtonValue = e.target.value
return (
<form onSubmit={formik.handleSubmit}>
<input
type="radio"
id="one"
name="group"
value="One"
onChange={e => handleRadioButtons(e)}
required
/>
<label htmlFor="one">One</label>
<br />
<input
type="radio"
id="two"
name="group"
value="Two"
onChange={e => handleRadioButtons(e)}
/>
<label htmlFor="two">Two</label>
<button type="submit">Submit</button>
</form>
)
}
Beware, if you use formik.values.radioButtonValue value as a useEffect dependency, then setting it like this: formik.values.radioButtonValue = e.target.value not gonna trigger the change, and useEffect won't launch (at least in my case it didn't). As an alternative, you gonna have to implement some kind of condition check with this value in your useEffect code
You need to map onChange like below.
<input
type="radio"
value="furnished"
name="currState"
onChange={getFieldProps("currState").onChange}
/>

Can't update state using useState

I'm trying to update the state of my component with useState in a register functional component。
when user input an invalid email address and click the submit button,
the following piece of code will return an error message
let response= await axios.post("/api/user/register",new_user,config);
I want to set error message into formData with this piece of code .
let response= await axios.post("/api/user/register",new_user,config);
if(response.data.errnum!==0){
setFormData({...formData,errors:response.data.message})
console.log(formData);
}
but the value of errors is empty,like this
What should I do to set error message into formData?
Here is my code:
import React ,{useState}from 'react'
import axios from "axios"
function Register() {
const [formData,setFormData]=useState({
name:"",
email:"",
password:"",
password2:"",
errors:{}
});
const {name,email,password,password2}=formData;
const setValue= e =>setFormData({...formData,[e.target.name]:e.target.value})
const submitData=async (e) =>{
e.preventDefault();
if(password!==password2){
console.log("passwords do not match ");
}else{
let new_user={name,email,password,}
try{
let config={
header:{
'Content-Type':'applicaiton/json'
}
}
let response= await axios.post("/api/user/register",new_user,config);
if(response.data.errnum!==0){
setFormData({...formData,errors:response.data.message})
console.log(formData);
}
}catch(error){
console.error(error);
}
}
}
return (
<div>
<section className="container">
<h1 className="large text-primary">Sign Up</h1>
<p className="lead"><i className="fas fa-user"></i> Create Your Account</p>
<form className="form" onSubmit={e=>submitData(e)}>
<div className="form-group">
<input
type="text"
placeholder="Name"
name="name"
value={name}
onChange={e=>setValue(e)}
required />
</div>
<div className="form-group">
<input
type="email"
placeholder="Email Address"
onChange={e=>setValue(e)}
value={email}
name="email" />
<small className="form-text">This site uses Gravatar so if you want a profile image, use aGravatar email</small>
</div>
<div className="form-group">
<input
type="password"
placeholder="Password"
onChange={e=>setValue(e)}
value={password}
name="password"
minLength="6"
/>
</div>
<div className="form-group">
<input
type="password"
placeholder="Confirm Password"
onChange={e=>setValue(e)}
value={password2}
name="password2"
minLength="6"
/>
</div>
<input type="submit" className="btn btn-primary" value="Register" />
</form>
<p className="my-1">
Already have an account? Sign In
</p>
</section>
</div>
)
}
export default Register
I think what you are doing wrong is that you are saving and object inside another object
const [formData,setFormData]=useState({
name:"",
email:"",
password:"",
password2:"",
errors:{}
});
formData is an object while errors is also an object.To go for a better approach make a seperate state for errors and append all the errors coming through those messages in an error object.
If you write a message in errors object where it is defined it will give you error
errors:{"hi","bye"}
There is no issue in your code. What you are trying to do is console the state as soon as you are setting it up.
setState is asynchronous which means you can’t call it on one line and assume the state has changed on the next.
If you check React docs
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
I'd suggest you use useEffect and then check for change in data of your state.
useEffect(() => {
console.log(formData)
}, [formData])

Form Submit using reactjs

I am new in reactjs. I am creating a sample project using reactjs. First I am getting error like state is null. After setting intial state i am getting error
I got Warning: valueLink prop on input is deprecated; set value and onChange instead
I know there are many question related to this but my problem is not solved please help.
Here is code:
import React, {Component} from 'react';
import {Link} from 'react-router'
import validator from 'validator';
import LinkedStateMixin from 'react-addons-linked-state-mixin';
module.exports = React.createClass({
mixins: [LinkedStateMixin],
getInitialState() {
return {};
},
saveData: function(){
//console.log(this.state)
},
render () {
return (
<form>
<div className="page-content container">
<div className="row">
<div className="col-md-4 col-md-offset-4">
<div className="login-wrapper">
<div className="box">
<div className="content-wrap">
<h6>Sign Up</h6>
<input className="form-control" name ="email" placeholder="E-mail address" type="text" valueLink={this.linkState('email')}/>
<input className="form-control" name="password" placeholder="Password" type="password"/>
<input className="form-control" placeholder="Confirm Password" type="password" />
<div className="action">
<button type="button" className ="btn btn-primary signup" onClick={this.saveData}>Sign Up</button>
</div>
</div>
</div>
<div className="already">
<p>Have an account already?</p>
<Link to ="/reactApp/">Login</Link>
</div>
</div>
</div>
</div>
</div>
</form>
)
}
});
Please read more about the fundamentals of React and handling state in forms in the React documentation. No mixins or anything complicated required. Also as stated above "ReactLink is deprecated as of React v15. The recommendation is to explicitly set the value and change handler, instead of using ReactLink."
Each of your text inputs should have a change handler just like the error message says... There are many ways you could accomplish this but below is a basic example. Check out the snippet below in a fiddle here https://jsfiddle.net/09623oae/
React.createClass({
getInitialState: function() {
return({
email: "",
password: "",
passwordConfirmation: ""
})
},
submitForm: function(e) {
e.preventDefault()
console.log(this.state)
},
validateEmail: function(e) {
this.setState({email: e.target.value})
},
validatePassword: function(e) {
this.setState({password: e.target.value})
},
confirmPassword: function(e) {
this.setState({passwordConfirmation: e.target.value})
},
render: function() {
return (
<form onSubmit={this.submitForm}>
<input
type="text"
value={this.state.email}
onChange={this.validateEmail}
placeholder="email"
/>
<input
type="password"
value={this.state.password}
onChange={this.validatePassword}
placeholder="password"
/>
<input
type="password"
value={this.state.passwordConfirmation}
onChange={this.confirmPassword}
placeholder="confirm"
/>
</form>
)
}
});
Solution
You cannot use valueLink anymore, instead use onChange react event to listen for input change, and value to set the changed value.
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'Hello!'};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
return (
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
);
}
Clarification
Notice that since the value is set from a state, it will only get updated from changing the attached state, writing in the input does nothing, unless you listen for the input changed (via onChange event) and update the state accordingly.
source: from React documentation
You should set your state to atleast empty initially, if you want to access it at a later point of time. Something similar to below will do
getInitialState() {
return {};
},
ReactLink Without valueLink
You can change with
<input type="text" value={valueLink.value} onChange={handleChange} />
Reference:
https://facebook.github.io/react/docs/two-way-binding-helpers.html
This warning happens because the React Link was deprecated in React 0.15:
ReactLink is deprecated as of React v15. The recommendation is to
explicitly set the value and change handler, instead of using
ReactLink.
So, instead of use this.linkState('email') and valueLink:
<input className="form-control"
name ="email"
placeholder="E-mail address"
type="text"
valueLink={this.linkState('email')}/>
Use this.state.email and an onChange function:
callThisWhenChangeEmail: function(emailFromInput) {
this.setState({
email: emailFromInput
});
},
render () {
/* the existent code above */
<input className="form-control"
name ="email"
placeholder="E-mail address"
type="text"
value={this.state.email}
onChange={this.callThisWhenChangeEmail}/>
/* the existent code below */
}
When the user type some e-mail in the input, the function callThisWhenChangeEmail is called, receiving the e-mail as parameter (emailFromInput). So, you only need to set this e-mail in the state.

Categories

Resources