How to deal with issue when user doesn't exist - javascript

When the user doesn't exist for this rather than redirecting to signup page I got this error, also I
tried something to change but unable to find how I can do it successfully
Menu.js
import React,{Fragment} from 'react';
import { Link ,withRouter} from 'react-router-dom'
import {signout,isAuthenticated} from '../auth'
import {itemTotal} from './CartHelper'
const isActive =(history,path)=>{
if(history.location.pathname === path){
return {color :'#ff9900'}
} else{
return {color:'#ffffff'}
}
}
/* here link component is similar to anchor tag in html */
const Menu =({history})=>{
//const {name,email,role} = isAuthenticated()
console.log('this is my history role ->',isAuthenticated());
return(
<div>
<ul className="nav nav-tabs bg-primary">
<li className="nav-list">
<Link className="nav-link" style={isActive (history,'/')} to="/">Home</Link>
</li>
<li className="nav-list">
<Link className="nav-link" style={isActive (history,'/shop')} to="/shop">Shop</Link>
</li>
<li className="nav-list">
<Link className="nav-link" style={isActive (history,'/cart')} to="/cart">Cart
<sup>
<small className="cart-badge">{itemTotal()}</small>
</sup>
</Link>
</li>
{isAuthenticated() && isAuthenticated().user.role === 0 && (
<li className="nav-list">
<Link className="nav-link" style={isActive (history,'/user/dashboard')} to="/user/dashboard">Dashboard</Link>
</li>
)}
{isAuthenticated() && isAuthenticated().user.role === 1 && (
<li className="nav-list">
<Link className="nav-link" style={isActive (history,'/admin/dashboard')} to="/admin/dashboard">Dashboard</Link>
</li>
)}
{!isAuthenticated() && (
<Fragment>
<li className="nav-list">
<Link className="nav-link" style={isActive (history,'/signin')}to="/signin">Signin</Link>
</li>
<li className="nav-list">
<Link className="nav-link" style={isActive (history,'/signup')} to="/signup">Signup</Link>
</li>
</Fragment>
)}
{isAuthenticated() && (
<li className="nav-list">
<span className="nav-link"
style={{cursor:'pointer',color:'#ffffff'}}
onClick={()=>signout(()=>{
history.push('/');
})
}>SignOut</span>
</li>
)}
</ul>
</div>
);
};
export default withRouter(Menu);
/*
*/
Signin.js
import React,{useState} from 'react';
import { Redirect } from 'react-router-dom'
import Layout from '../core/Layout';
import {signin,authenticate,isAuthenticated} from '../auth'
const Signin =()=>{
const [values,setValues] = useState({
email:'',
password:'',
error:'',
loading:false,
redirectToReferrer:false
})
// here we use redirectToReferrer because when it will be true user will be redirected to home page
// all the fields are streoed in value which is an object so we have to destructure to grab individual values
const {email,password,loading,error,redirectToReferrer} = values
// here we are destructing user and tring to divert user to admin if role === 1 (i.e admin) fir that we are destricting
const {user} = isAuthenticated();
// it is higer order function where one function return anither function
// also here name is like a parameter in which every name,email,apssword is copied to grab current valeu to update the sate
// here we use ...values to tell about our previous state values
const handleChange = name => event =>{
setValues({...values,error:false,[name]:event.target.value});
}
// now we have to send data to backend when user click on submit button so it can be done by this method
// we used preventDefault to stop auto reload of the page after an action is performed
const clickSubmit =(event)=>{
event.preventDefault();
setValues({...values,error:false,loading:true});
signin({email,password})
.then(data=>{
// console.log('my data in signin',data);
if(data.error){
console.log('my signing error after event fired',data.error);
setValues({...values,error:data.error,loading:false});
}
else{
authenticate(data,()=>{
setValues({...values,redirectToReferrer:true})
})
}
})
// we are passing all value as an object to user parameter
// signup({name:name,email:email,password:password})
// when key and values name are same so we can only write values
}
const signinForm =()=>(
<form>
<div className="form-group">
<label className="text-muted">Email</label>
<input onChange={handleChange('email')}
type ="email" className="form-control"
value={email}
/>
</div>
<div className="form-group">
<label className="text-muted">Password</label>
<input onChange={handleChange('password')}
type ="password" className="form-control" value={password}/>
</div>
<button onClick={clickSubmit} className="btn btn-primary">Submit</button>
</form>
);
const showError =()=>{
return <div className="alert alert-danger" style={{display:error?'':'none' }}>{error}</div>
}
const showLoading =()=>
loading && (<div className="alert alert-info"><h2>Loading...</h2></div>);
// here we are redirecting user based on hos role
// we have done authentication already so now if the user role is 1(admin then it will be redirected to admin dashboard else to user dashboard)
const redirectUser =()=>{
if(redirectToReferrer){
if(user && user.role === 1)
return <Redirect to="/admin/dashboard" />
}else{
return <Redirect to="/user/dashboard" />
}
}
if(isAuthenticated()){
return <Redirect to="/" />;
}
return(
<Layout
title="Signin"
description="Signin to Dashboard"
className="container col-md-8 offset-md-2">
{showLoading()}
{showError()}
{signinForm()}
{redirectUser}
</Layout>
)
}
export default Signin;
Signup.js
import React,{useState} from 'react';
import { Link } from 'react-router-dom'
import Layout from '../core/Layout';
import {signup} from '../auth'
const Signup =(user)=>{
const [values,setValues] = useState({
name:'',
email:'',
password:'',
error:'',
success:false
})
// all the fields are streoed in value which is an object so we have to destructure to grab individual values
const {name,email,password,success,error} = values
// it is higer order function where one function return anither function
// also here name is like a parameter in which every name,email,apssword is copied to grab current valeu to update the sate
// here we use ...values to tell about our previous state values
const handleChange = name => event =>{
setValues({...values,error:false,[name]:event.target.value});
}
// now we have to send data to backend when user click on submit button so it can be done by this method
// we used preventDefault to stop auto reload of the page after an action is performed
const clickSubmit =(event)=>{
event.preventDefault();
setValues({...values,error:false});
signup({name,email,password})
//console.log("this is my data ",data);
.then(data=>{
// console.log(data);
if(data.error){
setValues({...values,error:data.error,success:false});
}
else{
setValues({...values,name:'',email:'',password:'',error:'',success:true})
}
})
// we are passing all value as an object to user parameter
// signup({name:name,email:email,password:password})
// when key and values name are same so we can only write values
}
const signupForm =()=>(
<form>
<div className="form-group">
<label className="text-muted">Name</label>
<input onChange={handleChange('name')}
type ="text" className="form-control"
value={name}
/>
</div>
<div className="form-group">
<label className="text-muted">Email</label>
<input onChange={handleChange('email')}
type ="email" className="form-control"
value={email}
/>
</div>
<div className="form-group">
<label className="text-muted">Password</label>
<input onChange={handleChange('password')}
type ="password" className="form-control" value={password}/>
</div>
<button onClick={clickSubmit} className="btn btn-primary">Submit</button>
</form>
);
const showError =()=>{
return <div className="alert alert-danger" style={{display:error?'':'none' }}>{error}</div>
}
const showSuccess =()=>{
return <div className="alert alert-danger" style={{display:success?'':'none' }}>new account is created .Please <Link to="/signin">Signin</Link></div>
}
return(
<Layout
title="Signup"
description="Signup to node React E-commerce App"
className="container col-md-8 offset-md-2"
>
{showSuccess()}
{showError()}
{signupForm()}
</Layout>
)
}
export default Signup;
I have added all relevant file to know about the error also in which file I am getting error I have attached as well

Seems like the issue is that before redirecting the user you are trying to access a value that is undefined which is a no go and crashes the app.
What I try to do is initialize the user values (with strings or null values) and not assign them undefined values if the response from the server is bad.
if(data.error){
console.log('my signing error after event fired',data.error);
setValues({...values,error:data.error,loading:false});
}
This seems to be problematic.

Related

How to change the url for signin page in next-auth?

In Next.js project I've implemented authentication with Next-Auth.
In index.js (as the Next-Auth documentation explains) I return a User only if there is a session
export default function Home({characters}) {
const {data: session} = useSession()
return (
<>
<Meta
description="Generated by create next app"
title={!session ? "Home - Login" : `Home - ${session.user.name}`}
/>
{session ? <User session={session} /> : <Guest/>}
</>
)
}
In the Guest component I have a Sign In button, and the onClick event points to the signIn method from "next-auth/react"
function Guest() {
return <Layout className="flex flex-col h-screen">
<div className="font-extrabold mb-4 text-3xl">GUEST USER</div>
<Button onClick={() => signIn()}>Sign In</Button>
</Layout>
}
as soon as I click that button I'm redirected to this pages/auth/signin.js page.
This is the page where I can login through EmailProvider or GoogleProvider
import { getCsrfToken, getProviders, signIn } from "next-auth/react"
import { Meta, Layout, Card, InputGroup, Button } from "../../components/ui";
export default function SignIn({ csrfToken, providers }) {
return (
<Layout>
<Meta title="Login"/>
<Card>
<form method="post" action="/api/auth/signin/email">
<input name="csrfToken" type="hidden" defaultValue={csrfToken} />
<InputGroup
type="email"
htmlFor="email"
label="Email"
name="email"
/>
<Button type="submit">Sign in with Email</Button>
</form>
{Object.values(providers).map((provider) => {
if(provider.name === "Email") {
return
}
return (<div className="mt-3" key={provider.name}>
<Button onClick={() => signIn(provider.id)}>
Sign in with {provider.name}
</Button>
</div>)
})}
</Card>
</Layout>
)
}
export async function getServerSideProps(context) {
const csrfToken = await getCsrfToken(context)
const providers = await getProviders()
return {
props: { csrfToken, providers },
}
}
When I'm in this page the url is http://localhost:3000/auth/signin?callbackUrl=http%3A%2F%2Flocalhost%3A3000
I wanna know if it's possible to change that url to a more polite one like http://localhost:3000/login or something like this.
This page is already a custom login page as you can see in my [...nextauth].js
pages: {
signIn: '/auth/signin',
},
any suggestions? Thanks guys!
Yes it should work. Lets say you put this in your [...nextauth].js options
pages: {
signIn: '/login'
}
The signIn button will now redirect to /login.
Then you just have to put your login page under pages: pages/login.js.

pass some value back to parent component in next js

In my nextjs project I'm displaying posts from different tags and each post have many tags. I have a post_by_tags component and I'm using that component in different sections on home page to display posts from different tags. I don't want to show repeating content as some posts have same tags and I have a array to keep post ids that are visible to website. Now I want a way to keep post ids from child component to send back to parent component which updates the array so I can filter out these posts from post object. I find some examples but mostly these are tied with onclick or onchange something like that.
Here is my parent component code:
import Head from 'next/head'
import Image from 'next/image'
import Layout from '../components/Layout';
import Hero from '../components/Hero';
import Developed_country from '../components/Developed_country';
import Posts_by_tags from '../components/Post_by_tags';
import Attorneys from '../components/Attorneys';
import Business_formation from '../components/Business_formation';
import Case from '../components/Case';
export async function getServerSideProps(context) {
// Fetch data from external API
const res = await fetch(`https://dashboard.toppstation.com/api/blogs`);
const data = await res.json();
// Pass data to the page via props
return {
props: { blogs:data}
}
}
export default function Home({blogs}) {
const blog_post_id = [];
const pull_data = (data) => {
console.log(data); // LOGS DATA FROM CHILD)
}
return (
<Layout>
<Hero/>
<Developed_country/>
<Posts_by_tags tag='business' bg='bg_grey' posts={blogs} func={pull_data}/>
<Business_formation/>
<Attorneys/>
<Posts_by_tags tag='png' bg='bg_white' posts={blogs} />
<Posts_by_tags tag='image' bg='bg_grey' posts={blogs} />
<Posts_by_tags tag='png' bg='bg_white' posts={blogs} />
<Case/>
</Layout>
)
}
Child component:
import Blogimg from '../public/img/blog.png';
import btn_arrow from '../public/img/btn_arrow.svg';
import styles from '../styles/Home.module.css';
export default function Posts_by_tags(props){
props.func('My name is xyz');
const bg = props.bg;
let align = ['start','center','end'];
let post_tags = [];
const postIds= [];
const blog_posts = props.posts.filter(bpost=>{
bpost.tags.forEach(tag => {
if(tag.toLowerCase() === props.tag){
return postIds.push(bpost._id);
}
})
});
const posts = props.posts.filter(p => {
if( (postIds.indexOf(p._id) !== -1) && p.visibility==true){
return p;
}
}).slice(0,3);
return(
<>
{posts.length == 0 ? null :(
<section id={styles.postsbytags} className={bg}>
<div className='wrapper'>
<div className="container section posts_by_tags section_ptb">
<div className='row'>
<div className='col-sm-12'>
<h3 className={`${styles.heading3} text-center`}><span className={`${styles.heading3span} ${bg}`}>{props.tag}</span></h3>
</div>
</div>
<div className='row pt_100'>
{posts.map( (post, index) =>(
<div id={`post-${post._id}`} className={`col-md-4 d-flex justify-content-md-${align[index]} justify-content-center`} key={post._id}>
<div className={styles.blog_post}>
<div className={`${styles.blog_image} text-center`}>
<span className={styles.blog_tag}>{props.tag}</span>
<Image className="img-fluid" src={post.image} alt={post.title} width={450} height={400} layout='responsive'/>
</div>
<div className='blog_content'>
<h4 className={styles.blog_title}>{post.title}</h4>
<p className={styles.blog_desc}>{post.description.split(' ').slice(0, 10).join(' ')}...</p>
</div>
</div>
</div>
))}
</div>
<div className='row'>
<div className='col-sm-12'>
<div className='blog_category pt_50'>
<a href="" className={ `btn ${styles.btn_tags} `}>See More {props.tag} <i className={styles.btn_icon}><Image src={btn_arrow} alt="btn-icon"/></i></a>
</div>
</div>
</div>
</div>
</div>
</section>
)}
</>
);
}```

Prop is an empty object in React child

I'm trying to add a search bar to a parent component.
All the logic is working fine in the console. With every character that is typed in the search field I get fewer results.
I try to pass it to a child component to render the card(s) result, but I get a blank card: I can not see data passed.
Parent Component <AllAssets>
class AllAssets extends Component {
state = {
cards: [],
searchField: '',
}
async componentDidMount() {
const { data } = await cardService.getAllCards();
if (data.length > 0) this.setState({ cards: data });
}
addToFavorites = (cardId, userId) => {
saveToFavorites(cardId, userId)
toast.error("The asset was added to your favorites.")
}
render() {
const { cards, searchField } = this.state;
const user = getCurrentUser();
const filteredAssets = cards.filter(card => (
card.assetName.toLowerCase().includes(searchField.toLowerCase())));
console.log(filteredAssets);
return (
<div className="container">
<SearchBox placeholder={"Enter asset name..."}
handleChange={(e) => this.setState({ searchField: e.target.value })}
/>
<PageHeader>Assets available for rent</PageHeader>
<div className="row">
<div className="col-12 mt-4">
{cards.length > 0 && <p>you can also add specific assets to your favorites and get back to them later...</p>}
</div>
</div>
<div className="row">
{!!filteredAssets.length ? filteredAssets.map(filteredAsset => <SearchResult addToFavorites={this.addToFavorites} filteredAsset={filteredAsset} user={user} key={filteredAsset._id} />) :
cards.map(card => <CardPublic addToFavorites={this.addToFavorites} card={card} user={user} key={card._id} />)
}
</div>
</div >
);
}
}
export default AllAssets;
Child Component <SearchResult>
const SearchResult = (addToFavorites, filteredAsset, card, user) => {
return (
<div className="col-lg-4 mb-3 d-flex align-items-stretch">
<div className="card ">
<img
className="card-img-top "
src={filteredAsset.assetImage}
width=""
alt={filteredAsset.assetName}
/>
<div className="card-body d-flex flex-column">
<h5 className="card-title">{filteredAsset.assetName}</h5>
<p className="card-text">{filteredAsset.assetDescription}</p>
<p className="card-text border-top pt-2">
<b>Tel: </b>
{filteredAsset.assetPhone}
<br />
<b>Address: </b>
{filteredAsset.assetAddress}
</p>
<p>
<i className="far fa-heart text-danger me-2"></i>
<Link to="#" className="text-danger" onClick={() => addToFavorites(card._id, user._id)}>Add to favorites</Link>
</p>
</div>
</div>
</div>
);
}
export default SearchResult;
When I console.log(filteredAsset) in <SearchResult> I get an empty object. What am I doing wrong?
This line is incorrect:
const SearchResult = (addToFavorites, filteredAsset, card, user) => {
You are passing in positional arguments, not named props. Do this instead:
const SearchResult = ({addToFavorites, filteredAsset, card, user}) => {
In your original code, React attaches all of your props as fields on the first argument. So they would be accessible in the child, but not in the way you're trying to access them. Try logging out the values of each of the arguments in the child, if you're curious to see what happens.
The corrected version passes in a single object with field names that match the names of your props. It's shorthand that's equivalent to:
const SearchResult = (
{
addToFavorites: addToFavorites,
filteredAsset: filteredAsset,
card: card,
user: user,
}
) => {

How to show the comments from an API which is in tree form in react?

API: https://hn.algolia.com/api/v1/items/12701272
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import React, { useState } from "react";
// import "./index.css";
const Tree = ({ data = []}) => {
return (
<div className="d-tree">
<ul className="d-flex d-tree-container flex-column">
{data.map((tree) => (
<TreeNode node={tree} />
))}
</ul>
</div>
);
};
const TreeNode = ({ node }) => {
const [childVisible, setChildVisiblity] = useState(false);
const hasChild = node.children ? true : false;
return (
<li className="d-tree-node border-0">
<div className="d-flex" onClick={(e) => setChildVisiblity((v) => !v)}>
{hasChild && (
<div
className={`d-inline d-tree-toggler ${
childVisible ? "active" : ""
}`}
>
<FontAwesomeIcon icon="caret-right" />
</div>
)}
<div className="col d-tree-head">
<i className={`mr-1 `}> </i>
{node.text}
</div>
</div>
{hasChild && childVisible && (
<div className="d-tree-content">
<ul className="d-flex d-tree-container flex-column">
<Tree data={node.children} />
</ul>
</div>
)}
</li>
);
};
export default Tree;
I want to show all the comments in tree format,
I tried by above method but it shows error: TypeError: data.map is not a function
The data passed in tree function is the api converted into data.
What to do?
You are getting this error TypeError: data.map is not a function because data is not an array but an object. The response from the API is -
{
id:12701272,
created_at:"2016-10-13T15:15:48.000Z",
created_at_i:1476371748,
type:"story",
author:"fatihky",
title:"Google's “Director of Engineering” Hiring Test",
url:"http://www.gwan.com/blog/20160405.html",
text:null,
points:1764,
parent_id:null,
story_id:null,
children:(190) [...],
options:(0) [...]
}
The comment is inside the the object which is inside the array having children as the key.

How to give validation in multi step form using react

I am working on a scenario where I have to do a multi-step form which I have already done, as well as the validation part. I am using react-hook-form for validation.
I have multi-step form:
in the first form I have several fields and one radio button
by default radio button is ticked on for auto generated pass so in this case I have nothing to do
the second one is let me create a password so in this case one input field will be show and the user will create the password
Issue
In my final form I am doing the validation like below:
{
fields: ["uname", "email", "password"], //to support multiple fields form
component: (register, errors, defaultValues) => (
<Form1
register={register}
errors={errors}
defaultValues={defaultValues}
/>
)
},
So to validate uname, email and password I am passing the values like above.
But when the radio button is ticked for auto generated password it is still handling the validation, I click on next and it is not going to next for because of password field.
And if I check the radio button as let me create the password it goes to next form and when I came back by clicking back it is going to auto generated password again and it is not holding the previous state. For other input fields it is handling the previous values but not in case of radio button scenario.
My full working code sandbox
Answer 1 The reason is you fields: ["uname", "email", "password"] is fixed, password is always to be taken validation.
Solution Need to store state of Form1 in App so you can check if the state of auto generated password is on remove password from the list
App.js
... other code
// need to move state and function form Form to app
const [show_input, setshow_input] = useState(false);
const createInput = () => {
setshow_input(true);
};
const auto_text = () => {
setshow_input(false);
};
const forms = [
{
// validate based on show_input state
fields: show_input ? ["uname", "email", "password"] : ["uname", "email"], //to support multiple fields form
component: (register, errors, defaultValues) => (
<Form1
register={register}
errors={errors}
defaultValues={defaultValues}
auto_text={auto_text}
createInput={createInput}
show_input={show_input}
/>
)
},
{
fields: ["lname"],
component: (register, errors, defaultValues) => (
<Form2
register={register}
errors={errors}
defaultValues={defaultValues}
/>
)
},
{
component: (register, errors, defaultValues) => (
<Form3
register={register}
errors={errors}
defaultValues={defaultValues}
/>
)
}
];
... other code
Answer 2 When you go next the Form1 is unmounted so its state is destroyed. When you store Form1's state in App.js you will fix this issue too
Bonus: It's prefered to use camalCase (E.g: showInput) rather than underscore (show_input)
The main problem is that you render the forms conditionally so all the previous form values are removed. The solution for this is to keep all forms mounted and just use display: none or display: block depending on which form is selected. This way all values will be persisted whenever you go to next or prev form or submit the form.
The second problem that you didn't remove the password field when it's unmounted so when moveToNext is called the valid argument in triggerValidation callback is always false. I fixed that by setting the fields for Form1 conditionally depending on if the password input is visible or not.
The third problem you are using defaultValues for the wrong purpose. You can get the current form values using getValues() which will return all the current values of the form.
I set the default value for uname field just as an example to show you how defaultValues should be used.
you can check the full solution here: https://codesandbox.io/s/fragrant-forest-75pzs?file=/src/App.js
here are all the changed files:
App.js
import React, { useState } from "react";
import Form1 from "./components/Form1";
import Form2 from "./components/Form2";
import Form3 from "./components/Form3";
import { useForm } from "react-hook-form";
function MainComponent() {
const {
register,
triggerValidation,
defaultValues,
errors,
getValues
} = useForm({
// You can set default values here
defaultValues: {
uname: "Lol"
}
});
console.log("Errors: ", errors);
const [currentForm, setCurrentForm] = useState(0);
// control password input visibility and Form1 fields
const [passwordVisible, setPasswordVisible] = useState(false);
const showPassword = () => {
setPasswordVisible(true);
};
const hidePassword = () => {
setPasswordVisible(false);
};
const forms = [
{
fields: passwordVisible
? ["uname", "email", "password"]
: ["uname", "email"],
component: (register, errors) => (
<Form1
// a key is needed to render a list
key={0}
// this will be used to set the css display property to block or none on each form
shouldDisplay={currentForm === 0}
register={register}
errors={errors}
showPassword={showPassword}
hidePassword={hidePassword}
passwordVisible={passwordVisible}
/>
)
},
{
fields: ["lname"],
component: (register, errors) => (
<Form2
key={1}
shouldDisplay={currentForm === 1}
register={register}
errors={errors}
/>
)
},
{
component: (register, errors) => (
<Form3
key={2}
shouldDisplay={currentForm === 2}
register={register}
errors={errors}
values={getValues()}
/>
)
}
];
const moveToPrevious = () => {
triggerValidation(forms[currentForm].fields).then(valid => {
if (valid) setCurrentForm(currentForm - 1);
});
};
const moveToNext = () => {
triggerValidation(forms[currentForm].fields).then(valid => {
if (valid) setCurrentForm(currentForm + 1);
});
};
const prevButton = currentForm !== 0;
const nextButton = currentForm !== forms.length - 1;
const handleSubmit = e => {
console.log("whole form data - ", getValues());
};
return (
<div>
<div className="progress">
<div>{currentForm}</div>
</div>
{forms.map(form => form.component(register, errors))}
{prevButton && (
<button
className="btn btn-primary"
type="button"
onClick={moveToPrevious}
>
back
</button>
)}
{nextButton && (
<button className="btn btn-primary" type="button" onClick={moveToNext}>
next
</button>
)}
{currentForm === 2 && (
<button
onClick={handleSubmit}
className="btn btn-primary"
type="submit"
>
Submit
</button>
)}
</div>
);
}
export default MainComponent;
Form1
import React from "react";
function Form1({
register,
errors,
shouldDisplay,
passwordVisible,
showPassword,
hidePassword
}) {
return (
<div style={{ display: shouldDisplay ? "block" : "none" }}>
<form autoComplete="on">
<br />
<div className="form-group">
<label>User name</label>
<input type="text" name="uname" ref={register({ required: true })} />
{errors.uname && <span>required</span>}
<label>Email</label>
<input type="email" name="email" ref={register({ required: true })} />
{errors.email && <span>required</span>}
</div>
<div>
<div className="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
<label className="form_label">Password</label>
<div className="form-check">
<label>
<input
type="radio"
name="auto_pass"
id="Radios1"
value="auto_pass"
className="form-check-input"
defaultChecked={true}
onChange={hidePassword}
/>
Auto generated password
</label>
</div>
<div className="form-check">
<label>
<input
type="radio"
name="auto_pass"
id="Radios2"
value="let_me"
className="form-check-input"
onChange={showPassword}
/>
Let me create the password
</label>
</div>
</div>
{passwordVisible && (
<div className="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 mb-3">
<label className="form_label">Password</label>
<input
type="password"
name="password"
className="form-control"
ref={register({ required: true })}
/>
{errors.password && (
<span className="text-danger">Password is reguired</span>
)}
</div>
)}
</div>
</form>
</div>
);
}
export default Form1;
Form2
import React from "react";
function Form2({ register, errors, shouldDisplay }) {
return (
<div style={{ display: shouldDisplay ? "block" : "none" }}>
<form autoComplete="on">
<br />
<div className="form-group">
<label>User last name</label>
<input type="text" name="lname" ref={register({ required: true })} />
{errors.lname && <span>required</span>}
</div>
</form>
</div>
);
}
export default Form2;
Form3
import React from "react";
function Form3({ values, shouldDisplay }) {
return (
<div style={{ display: shouldDisplay ? "block" : "none" }}>
<h3>Want to display all values here like below</h3>
{Object.entries(values).map(([key, value]) => (
<p key={key}>
{key}: {value}
</p>
))}
<br />
<p>So that use can check for any Wrong info</p>
</div>
);
}
export default Form3;

Categories

Resources