React update state showing other component - reactjs

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>
);

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 update a state, by taking reference of other state

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)
}
}

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 get the value from button group in react component

Below is the button group component which I used inside the form.How to implement the onchange functions to this button group.I have no Idea how to set the onchange method
import React, {Component} from "react";
import {Popover, OverlayTrigger} from 'react-bootstrap';
import "./ButtonGroup.scss";
const popoverBottom = () =>{
return (
<Popover className="tooltip-popover" title="Here is the where you
give a tooltip">
</Popover>
);
}
export const ButtonGroup = ({
tooltip,
label,
options,
selected,
lableStyle = {},
Title = "Tooltip on top",
}) => {
return (
<div className="nuclei-group">
<p className="nuclei-buttongroup-input"> {label} </p>
<div data-toggle="buttons">
{options.map((option, i) => {
const className = selected == option.value ? "active" : "";
return (
<label
key={i}
style={lableStyle}
className={`btn btn-default nuclei-selection-option ${className}`}
>
<input
type="radio"
name={"name"}
id={option.value}
autoComplete="off"
/>
{option.label}
</label>
);
})}
{tooltip ? (
<span>
<OverlayTrigger trigger="click" rootClose placement="bottom" overlay={popoverBottom()}>
<button type="button" className="btn nuclei-tooltip">?</button>
</OverlayTrigger>
</span>
) : null}
</div>
</div>
);
};
export default ButtonGroup;
then I tried to add on change as below and after submitting the form it doesn't work can somebody help me to resolve it.Normally inside a input tag it works but here? and let me know is this the best way to get values from a form as in the code below
import React, {Component} from "react";
import "./classic-quote.scss";
import {Button, ButtonGroup, InputText} from "../../../components";
import StepBreadcrumb from "../../../components/StepBreadcrumb";
import HeaderTitle from "../../../components/HeaderTitle";
import axios from 'axios';
export default class ClassicQuote extends Component {
constructor(props){
super(props);
this.state = {
insurance_type:'',
vehicle_registration:'',
lease_loan_hire:'',
estimated_market_value:'',
usage:'',
make:'',
model:'',
year:'',
claim_bonus_year:''
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange1 = this.handleChange1.bind(this);
this.handleChange2 = this.handleChange2.bind(this);
this.handleChange3 = this.handleChange3.bind(this);
this.handleChange4 = this.handleChange4.bind(this);
}
handleChange1(e){
this.setState({
make: e.target.value
})
}
handleChange2(e){
this.setState({
model: e.target.value
})
}
handleChange3(e){
this.setState({
year: e.target.value
})
}
handleChange4(e){
this.setState({
insurance_type: e.target.id
})
}
handleSubmit(e){
e.preventDefault();
const quotation = {
make: this.state.make,
model: this.state.model,
year: this.state.year,
insurance_type: this.state.insurance_type
}
console.log('gggggggg'+quotation.make+quotation.model+quotation.year+quotation.insurance_type);
let uri = '/items'
axios.post(uri,quotation).then(response => {
console.log('ela');
}).then(error => {
console.log(error);
});
}
render() {
return <div>
{/* <StepBreadcrumb id="bred" /> */}
<div className="container insureme-form zero-padding">
<form onSubmit={this.handleSubmit}>
<div className="row">
<HeaderTitle mainFirstWord="Insurance" restOfTitle="Detail" headerStyle={{fontWeight: "bold"}} headerIcon={true} />
<div className="nuclei-insurance-detail-step-one">
<div className="col-md-12 col-sm-12 col-xs-12">
<ButtonGroup onChange={this.handleChange4} label="" selected="full" options={[{label: "Full Insurance", value: "full"}, {label: "3rd Party Insurance", value: "3rd"}]} tooltip />
<pre>{JSON.stringify(this.state, '', 2)}</pre>
</div>
<div className="col-md-12 col-sm-12 col-xs-12">
<ButtonGroup label="Do you have a vehicle registration No?" selected="Yes" options={[{label: "Yes", value: "Yes"}, {label: "No", value: "No"}]} tooltip />
</div>
<div className="col-md-12 col-sm-12 col-xs-12">
<ButtonGroup label="Do you have any lease,Loan or hire on vehicle?" selected="Yes" options={[{label: "Yes", value: "Yes"}, {label: "No", value: "No"}]} tooltip />
</div>
<div className="col-md-4 col-sm-4 col-xs-8">
<InputText label={"Estimated Market Value?"} placeholder="Rs." />
</div>
<div className="col-md-12 col-sm-12 col-xs-12">
<ButtonGroup label="Usage?" selected="Private" options={[{label: "Private", value: "Private"}, {label: "Hire", value: "Hire"}, {label: "Rent", value: "Rent"}]} tooltip />
</div>
<div className="col-md-12 col-sm-12 col-xs-12 form-group input-text ">
<label>Make, Model and Year of Manufacture? </label>
<div className="col-md-4 col-sm-4 col-xs-4 zero-padding-left">
<input type="text" className="form-control" id={"make-manufacture"} placeholder={"Make"} onChange={this.handleChange1} />
</div>
<div className="col-md-3 col-sm-3 col-xs-4 zero-padding-left">
<input type="text" className="form-control" id={"model-manufacture"} placeholder={"Model"} onChange={this.handleChange2}/>
</div>
<div className="col-md-2 col-sm-2 col-xs-3 zero-padding-left">
<input type="text" className="form-control" id={"year-manufacture"} placeholder={"Year"} onChange={this.handleChange3}/>
</div>
</div>
<div className="col-md-12 col-sm-12 col-xs-12 form-group input-text">
<label>No Claims Bonus?</label>
<div className="col-md-4 col-sm-4 col-xs-8 zero-padding-left">
<InputText tooltip placeholder="No. of Years" />
</div>
</div>
<div className="col-md-12 col-sm-12 col-xs-12">
<Button type="submit" color="red" className="nuclei-bottom-red-button">
Get a Quick Quote
</Button>
<Button type="clear" color="gray" className="nuclei-bottom-gray-button">
Clear
</Button>
</div>
</div>
</div>
</form>
</div>
</div>;
}
}
I tried several ways can get only the make model and year values as printed in the console log
if you want to pass an handler like this:
onChange={this.handleChange4}
you have to add it to the props you receive in Component:
export const ButtonGroup = ({
onChange,
tooltip,
label,
options,
selected,
lableStyle = {},
Title = "Tooltip on top",
}) => {
...
and then in the input elements call onChange:
<input
onChange={onChange}
type="radio"
name={"name"}
id={option.value}
autoComplete="off"
/>
If you want to see the complete solution, I build it in sandbox: Full example here
I saw that you update the form, but you didn't add "onChange" in the ButtonGroup Component file like in the comment:
export const ButtonGroup = ({
onChange, <---this
tooltip,
label,
options,
selected,
lableStyle = {},
Title = "Tooltip on top",
}) => {
return (
<div className="nuclei-group">
<p className="nuclei-buttongroup-input"> {label} </p>
<div data-toggle="buttons">
{options.map((option, i) => {
const className = selected == option.value ? "active" : "";
return (
<label
key={i}
style={lableStyle}
className={`btn btn-default nuclei-selection-option ${className}`}
>
<input
onChange={onChange} <---this
type="radio"
name={"name"}
id={option.value}
autoComplete="off"
/>
{option.label}
</label>
);
})}

Resources