How to update a state, by taking reference of other state - reactjs

I am working on a React project In my project I have two components one is Parent and another one is Child. In Parent component I have two buttons, one is Signup button and another one is Login Button. I imported Child component to Parent component, In Child component I have only Signup form is there. So I put state for Child component, that state logic contains initially Child component has to hide when I click Sigup button at that time only I have to show Child component up to here I have done. But here I was struck, When I click Signup button then I have hide both Signup and Login buttons, In output I have to show only Signup form.
This is Parent.js
import React, { useState } from 'react';
import Child from './Child/Child'
import './Parent.css';
const Parent = () => {
const [show, setShow] = useState(false)
const [showButtons, setShowButtons] = useState(true)
const showComponent = () => {
setShow(true)
}
const hideButtons = () => {
if(setShow(true)) {
setShowButtons(false)
}
}
return (
<div className='container'>
<div className='row'>
{showButtons &&
<div className='col-12' style={{display:"flex"}}>
<div className='col-6'>
<button className='btn btn-primary' onClick={() => {hideButtons(); showComponent()}}>Signup Form</button>
</div>
<div className='col-6'>
<button className='btn btn-danger'>Login Form</button>
</div>
</div>
}
</div>
<div className='row'>
<div className='col-12'>
{show && <Child></Child> }
</div>
</div>
</div>
)
}
export default Parent
This is Child.js
import React, { useState } from 'react';
import './Child.css';
const Child = () => {
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-6'>
<div className='signupForm'>
<form>
<div className="form-group">
<label htmlFor="name">Name</label>
<input type="text" className="form-control" id="name" placeholder="Enter name"></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input type="email" className="form-control" id="email" placeholder="Enter email"></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" id="password" placeholder="Enter password"></input>
</div>
<div className="form-group">
<label htmlFor="confirmPassword">Confirm Password</label>
<input type="password" className="form-control" id="confirmPassword" placeholder="Confirm password"></input>
</div>
<button type="submit" className="btn btn-primary mt-3">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Child
If you think I am not clear with question please ask me where I am not clear

Do the following change in your parent.js then it will work
const hideButtons = () => {
setShowButtons(false);
};
Codesandbox here

You are currently testing your setShow function for truthiness, but you want to test its corresponding value. So change your hideButtons function to this:
const hideButtons = () => {
if(show) {
setShowButtons(false)
}
}

Related

Clicking on react button asks me to leave site

I am learning react and I have a component which as a 2 input fields and a button, at the moment, clicking on the button will display a message in console log, but when the button is clicked it displays a popup Leave site?, Changes that you made may not be saved.
this is my code in this component
import React, { useRef, useState, Component } from 'react'
import { useAuthState } from 'react-firebase-hooks/auth';
import { useCollectionData } from 'react-firebase-hooks/firestore';
import { signOut } from 'firebase/auth';
class InfoLgnTest extends Component {
render() {
this.state = {
user: null
}
return (
<div>
<div className="App">
<SignInWithEmailPassword />
</div>
</div>
)
}
}
function SignInWithEmailPassword() {
const emailRef = useRef()
const passwordRef = useRef()
const signIn = () => {
console.log("InfoLgnTest singin clicked")
}
return (
<>
<div className="form">
<form>
<div className="input-container">
<label>Username </label>
<input
name="email"
type="text"
ref={emailRef}
required
placeholder ="something#gmail.com"
/>
</div>
<div className="input-container">
<label>Password </label>
<input
type="text"
name="pass"
ref={passwordRef}
required
placeholder ="..."
/>
</div>
<div className="button-container">
<input type="submit" onClick={signIn}/>
</div>
</form>
</div>
</>
)
}
export default InfoLgnTest
This code has a form, by default form send data as a request on the same page, for resolve this:
Add onSubmit to form,
call preventDefault method from event
call the function signIn
Change <input type="submit" ... /> to <button type="submit">Send</button>
function SignInWithEmailPassword() {
const emailRef = useRef()
const passwordRef = useRef()
const signIn = () => {
console.log("InfoLgnTest singin clicked")
}
// new function to handle submit
const submitForm = (event) => {
event.preventDefault();
signIn();
}
return (
<>
<div className="form">
{/* Add onSubmit */}
<form onSubmit={submitForm}>
<div className="input-container">
<label>Username </label>
<input
name="email"
type="text"
ref={emailRef}
required
placeholder ="something#gmail.com"
/>
</div>
<div className="input-container">
<label>Password </label>
<input
type="text"
name="pass"
ref={passwordRef}
required
placeholder ="..."
/>
</div>
<div className="button-container">
{/* Change input to button */}
<button type="submit">Send</button>
</div>
</form>
</div>
</>
)
}

Problems with react for animation

i have the login page without the js animation
after i add the animation code i dont get a render in the login page,
i use this to add the annimation
const signUpButton = document.getElementById('signUp')
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');
signUpButton.addEventListener('click', () => {
container.classList.add("right-panel-active");
});
signInButton.addEventListener('click', () => {
container.classList.remove("right-panel-active");
});
Here's the code:
import React from 'react';
const Loginpart = () => {
return (
<div>
<section className="position-relative pb-0">
<div className="gen-login-page-background" ></div>
<div className="container" id="container">
<div className="form-container sign-up-container">
<form action="#">
<h1 >Create Account</h1>
<span>or use your email for registration</span>
<input type="text" placeholder="Name" />
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
<button>Sign Up</button>
</form>
</div>
<div className="form-container sign-in-container">
<form action="#">
<h1 >Sign in</h1>
<span>or use your account</span>
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
Forgot your password?
<button>Sign In</button>
</form>
</div>
<div className="overlay-container">
<div className="overlay">
<div className="overlay-panel overlay-left">
<h1>Welcome Back!</h1>
<p>To keep connected with us please login with your personal info</p>
<button className="ghost" id="signIn">Sign In</button>
</div>
<div className="overlay-panel overlay-right">
<h1>Hello, Friend!</h1>
<p>Enter your personal details and start journey with us</p>
<button className="ghost" id="signUp">Sign Up</button>
</div>
</div>
</div>
</div>
</section>
</div>
);
};
export default Loginpart;
this is the code for animation :
const signUpButton = document.getElementById('signUp')
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');
signUpButton.addEventListener('click', () => {
container.classList.add("right-panel-active");
});
signInButton.addEventListener('click', () => {
container.classList.remove("right-panel-active");
});
Chances are, when you start the handler functions, the Loginpart component still hasn't rendered.
Check the constants if they are undefined.
Perhaps this approach is more suitable for you with react
import React, {useState} from 'react'
const Component=()=>{
const [anime, setAnime] = useState(false)
function handleAnimation(){
setAnime(!anime)
}
<div id='container' className={`container ${anime&&'right-panel-active'}`}>
<button onClick={handleAnimation}></button>
</div>
}
export default Component
There are actually several ways to do this, css-in-js, or even with pure javascript, but you would have to ensure that the component is already assembled.

How to write validations for Input tag in react?

I am working on React project In my project I have to write validations for Input tag.
My goal is I have an Input tag, that Input tag type is number, Now I have to write validations like this
in that Input tag it has to take only six digits. And I cannot put like this -100000. it only has to take only digits no other symbols.
This is my code
import React from 'react';
import './App.css';
function App() {
return (
<div className="container">
<div className='row'>
<div className='col-4'>
<form>
<div className="form-group">
<label for="pincode">Pincode</label>
<input type="number" className="form-control" id="pin" placeholder="Enter Pincode"></input>
</div>
<button type="submit" className="btn btn-primary mt-5">Submit</button>
</form>
</div>
</div>
</div>
);
}
export default App;
If you have any questions please let me know
I think that You can use React-useRef hook. For example
const [input, setInput] = useState([])
const number = useRef()
const handleSubmit = (event) => {
//i said to react, i will do it myself
event.preventDefault();
const pincode = number.current.value
const data = {
pincode: pincode
}
if(data.pincode){
setInput([...input, data])
number.current.value = 0
}else{ console.log("oops")}
}
return (
<div className="container">
<div className='row'>
<div className='col-4'>
<form onSubmit = {handleSubmit}>
<div className="form-group">
<label for="pincode">Pincode</label>
<input ref = {number} type="number" className="form-control" id="pin" placeholder="Enter Pincode"></input>
</div>
<button onClick = {handleSubmit}type="submit" className="btn btn-primary mt-5">Submit</button>
</form>
</div>
</div>
</div>
)

How to pass a Child component state to Parent Component state in React

I am working on a React project, In my project I have two components Studentslist and Card.
In Studentslist component I have two buttons, one is Hockey and another one is Cricket.
Now when I click the Cricket button, then only Card component will show I have written logic like
That. Here Card component is Child to Studentslist component. In that Card component I have two
Buttons they are submit and cancel. Here when I click the cancel button on Card component the
Card component has to hide, but its not working. I think I have to write logic like this I have
To write one function in Card component and I have to pass that function to Studentslist
Component and that function have to update the state of the Student list component.
Please help me to solve this
If you feel I am not clear with my doubt, please put a comment.
This is Studentslist.js
import React, { useState } from 'react';
import './Studentslist.css';
import Card from '../../Components/Card/Card';
function Studentslist() {
const [show, setShow] = useState(false);
return (
<div className='container'>
<div className='row'>
<div className='col-12'>
<div className='Departments'>
<button className='btn btn-primary'>Hockey</button>
<button onClick={() => setShow(true)} className='btn btn-primary ml-2'>Cricket</button>
</div>
{show && <Card></Card>}
</div>
</div>
</div>
)
}
export default Studentslist
This is Card.js
import React, { useState } from 'react';
import './Card.css';
function Card() {
const [show, hide] = useState(true)
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-6'>
<div className='Registration'>
<form>
<div className="form-group">
<label htmlFor="firstname">Firstname</label>
<input type="text" className="form-control" id="firstname"></input>
</div>
<div className="form-group">
<label htmlFor="lastname">Lastname</label>
<input type="text" className="form-control" id="lastname"></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input type="email" className="form-control" id="email"></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" id="password"></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
<button type="button" onClick={() => hide(false)} className='cancel btn btn-danger ml-2'>Cancel</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Card
you can not pass children state to parent, you can pass setShow to cardComponent as props
{show && <Card setShow={() => setShow(false)}></Card>}
and in cardComponent you can use like below
function Card({ setShow }) {
...
<button type="button" onClick={setShow} className='cancel btn btn-danger ml-2'>Cancel</button>

React update state showing other component

I have react form state. After submitting the form I want to send the input values to other component and then showing to browser. I successfully submit the form but when I sent the porps to other component. It does not show anything.
Here is my hero component
import React from "react";
import "./App.css";
import Show from "./Show";
function App() {
const [state, setState] = React.useState({
input: " ",
text: " "
});
const changeHandler = e => {
setState({ ...state, [e.target.id]: e.target.value });
};
const handleSubmit = e => {
e.preventDefault();
console.log(state);
return <Show show={state} />; //this is the component where I am sending props
};
return (
<React.Fragment>
<div className="row">
<form className="col s12" onSubmit={handleSubmit}>
<div className="row">
<div className="input-field col s3">
<input
id="input"
type="text"
data-length="4"
onChange={changeHandler}
/>
<label htmlFor="input_text">Input text</label>
</div>
</div>
<div className="row">
<div className="input-field col s8">
<textarea
id="text"
className="materialize-textarea"
data-length="120"
onChange={changeHandler}
></textarea>
<label htmlFor="textarea2">Right your text</label>
</div>
</div>
<button
className="btn waves-effect blue lighten-1"
type="submit"
name="action"
>
Submit
</button>
</form>
<Show /> //After submit the form I want to show to the browser
</div>
</React.Fragment>
);
}
export default App;
Here is my child component.
import React from "react";
export default function Show({ show }) {
return (
<div>
{show ? (
<ul>
<li>{show.input}</li>
<li>{show.text}</li>
</ul>
) : null}
</div>
);
}
ps: Ignore this message.In order to upload this post I need to. write more 😀.
Calling Method was wrong
handleSubmit is the event activity call .its not component
Inside the handleSubmit component return is not right one
So better pass state value on Show component inside the parent fragment
const handleSubmit = e => {
e.preventDefault();
console.log(state);
};
return (
<React.Fragment>
<div className="row">
<form className="col s12" onSubmit={handleSubmit}>
<div className="row">
<div className="input-field col s3">
<input
id="input"
type="text"
data-length="4"
onChange={changeHandler}
/>
<label htmlFor="input_text">Input text</label>
</div>
</div>
<div className="row">
<div className="input-field col s8">
<textarea
id="text"
className="materialize-textarea"
data-length="120"
onChange={changeHandler}
></textarea>
<label htmlFor="textarea2">Right your text</label>
</div>
</div>
<button
className="btn waves-effect blue lighten-1"
type="submit"
name="action"
>
Submit
</button>
</form>
<Show show={state} /> //pass state directly
</div>
</React.Fragment>
);

Resources