I have a Home component that fetches data from the database and show it.
import React, {Component} from 'react';
import { Jumbotron,Modal,Button,ModalHeader,ModalBody,
Form,FormGroup,Input,Label} from 'reactstrap';
import { Card, CardTitle, CardText, Row, Col } from 'reactstrap';
import { CardHeader, CardFooter, CardBody } from 'reactstrap';
import axios from 'axios';
import BlogAddForm from './BlogAddForm';
import NavbarComponent from './NavbarComponent';
class HomeComponent extends Component{
constructor(){
super();
this.state={
isSignupModalOpen:false,
isLoginModalOpen:false,
isblogOpen:false,
blogs:[]
}
this.toggleSignupModal=this.toggleSignupModal.bind(this);
this.toggleLoginModal=this.toggleLoginModal.bind(this);
this.toggleblogModal=this.toggleblogModal.bind(this);
}
componentDidMount() {
console.log("component did mount");
axios.get('http://localhost:3000/')
.then(response => {
if (response.data.length > 0) {
this.setState({
blogs: response.data
});
}
})
.catch((error) => {
console.log(error);
})
}
toggleSignupModal(){
this.setState({
isSignupModalOpen:!this.state.isSignupModalOpen
})
}
toggleLoginModal(){
this.setState({
isLoginModalOpen:!this.state.isLoginModalOpen
})
}
toggleblogModal(){
this.setState({
isblogOpen:!this.state.isblogOpen
})
}
render(){
console.log("inside render ");
var b=this.state.blogs.map((blog)=>{
console.log(blog);
var taggu=blog.tags.map((tag)=>{
return(
<span>#{tag}</span>
)
});
var con=blog.content.slice(0,100);
return(
<Col className="my-1" lg="4" sm="6" >
<Card key={blog._id}>
<CardHeader tag="h3">{blog.topic}</CardHeader>
<CardBody>
<CardTitle tag="h5">By {blog.writer.username}</CardTitle>
<CardText>{con}... </CardText>
<Button>Learn More</Button>
</CardBody>
<CardFooter>{taggu}</CardFooter>
</Card>
</Col>
)
});
return (
<div className="App">
<NavbarComponent />
<Jumbotron>
<h1 className="display-5">WELCOME TO BLOGERA</h1>
<p className="lead">This is a simple blog site where you can put your thoughts into words and
interact with people.</p>
<p className="my-2">
<Button color="success" onClick={this.toggleblogModal}>Add Blog</Button>
</p>
</Jumbotron>
{b}
<Modal isOpen={this.state.isLoginModalOpen} toggle={this.toggleLoginModal}>
<ModalHeader toggle={this.toggleLoginModal}>Login</ModalHeader>
<ModalBody>
<Form onSubmit={this.handleLogin}>
<FormGroup>
<Label htmlFor="username">Username</Label>
<Input type="text" id="username" name="username" innerRef=
{(input)=>this.username=input}/>
</FormGroup>
<FormGroup>
<Label htmlFor="password">Password</Label>
<Input type="password" id="password" name="password" innerRef=
{(input)=>this.password=input} />
</FormGroup>
<FormGroup check>
<Label check>
<Input type="checkbox" name="remember" innerRef=
{(input)=>this.remember=input}/>
Remember me
</Label>
</FormGroup>
<Button type="submit" value="submit" color="primary">Login</Button>
</Form>
</ModalBody>
</Modal>
<Modal isOpen={this.state.isSignupModalOpen} toggle={this.toggleSignupModal}>
<ModalHeader toggle={this.toggleSignupModal}>Signup</ModalHeader>
<ModalBody>
<Form onSubmit={this.handleLogin}>
<FormGroup>
<Label htmlFor="username">Username</Label>
<Input type="text" id="username" name="username" innerRef=
{(input)=>this.username=input}/>
</FormGroup>
<FormGroup>
<Label htmlFor="password">Password</Label>
<Input type="password" id="password" name="password" innerRef=
{(input)=>this.password=input} />
</FormGroup>
<FormGroup check>
<Label check>
<Input type="checkbox" name="remember" innerRef=
{(input)=>this.remember=input}/>
Remember me
</Label>
</FormGroup>
<Button type="submit" value="submit" color="primary">Signup</Button>
</Form>
</ModalBody>
</Modal>
<Modal isOpen={this.state.isblogOpen} toggle={this.toggleblogModal}>
<ModalHeader toggle={this.toggleblogModal}>Write Blog</ModalHeader>
<ModalBody>
<BlogAddForm toggleblogModal={this.toggleblogModal} />
</ModalBody>
</Modal>
<Row>
<Col className="my-1" lg="4" sm="6" >
<Card>
<CardHeader tag="h3">Header</CardHeader>
<CardBody>
<CardTitle tag="h5">Special Title Treatment</CardTitle>
<CardText>With supporting text below as a natural lead-in to additional content.</CardText>
<Button>Learn More</Button>
</CardBody>
<CardFooter>Footer</CardFooter>
</Card>
</Col>
<Col className="my-1" lg="4" sm="6" >
<Card>
<CardHeader tag="h3">Featured</CardHeader>
<CardBody>
<CardTitle tag="h5">Special Title Treatment</CardTitle>
<CardText>With supporting text below as a natural lead-in to additional content.</CardText>
<Button>Learn More</Button>
</CardBody>
<CardFooter className="text-muted">Footer</CardFooter>
</Card>
</Col>
<Col className="my-1" lg="4" sm="6" >
<Card>
<CardHeader tag="h3">Featured</CardHeader>
<CardBody>
<CardTitle tag="h5">Special Title Treatment</CardTitle>
<CardText>With supporting text below as a natural lead-in to additional content.</CardText>
<Button>Learn More</Button>
</CardBody>
<CardFooter className="text-muted">Footer</CardFooter>
</Card>
</Col>
</Row>
</div>
);
}
}
export default HomeComponent;
BLOGADDFORM IS a component which takes data and send post request at backend. I want that as database gets updated my homecomponent should re render with the updated data. I tried redirecting to my home component but that does not solve the purpose.
this is my blog add form component
import React, {Component} from 'react';
import { Button,Form,FormGroup,Input,Label} from 'reactstrap';
import { Redirect } from 'react-router-dom';
import axios from 'axios';
class BlogAddForm extends Component{
constructor(){
super();
this.state = {
input: {},
errors: {}
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
let input = this.state.input;
input[event.target.name] = event.target.value;
this.setState({
input:input
});
}
handleSubmit(event) {
event.preventDefault();
if(this.validate()){
console.log(this.state);
axios.post("http://localhost:3000/nb", {
params:{
data:this.state.input
}
}).then((res)=>{
let input = {};
input["topic"] = "";
input["content"] = "";
input["tag"] = "";
this.setState({input:input});
alert('Blog Added');
this.props.toggleblogModal();
<Redirect to='/' />
}).catch((err)=>{
console.log(err);
})
}
}
validate(){
let input = this.state.input;
let errors = {};
let isValid = true;
if (!input["topic"]) {
isValid = false;
errors["topic"] = "Please enter the topic of blog.";
}
if (!input["content"]) {
isValid = false;
errors["content"] = "Please write some content.";
}
if (!input["tag"]) {
isValid = false;
errors["tag"] = "Please enter tags related to this blog.";
}
this.setState({
errors: errors
});
return isValid;
}
render(){
return(
<Form onSubmit={this.handleSubmit}>
<FormGroup>
<Label htmlFor="topic">Topic</Label>
<Input type="text" id="topic" name="topic"
value={this.state.input.topic}
onChange={this.handleChange}
/>
<div className="text-danger">{this.state.errors.topic}</div>
</FormGroup>
<FormGroup>
<Label htmlFor="content">Content</Label>
<Input type="textarea" id="content" name="content" rows={8}
value={this.state.input.content}
onChange={this.handleChange}
/>
<div className="text-danger">{this.state.errors.content}</div>
</FormGroup>
<FormGroup>
<Label htmlFor="tag">Tags</Label>
<Input type="text" id="tag" name="tag"
value={this.state.input.tag}
onChange={this.handleChange}
/>
<div className="text-danger">{this.state.errors.tag}</div>
</FormGroup>
<Button type="submit" value="submit" color="primary">Submit</Button>
</Form>
)
}
}
export default BlogAddForm;
You'll need to use componentDidUpdate() when reentering the Home component view.
Extract your network request into a different function and call it from both componentDidMount() and componentDidUpdate().
Related
It supposed to add the student list when I click on the button, but it doesn't.
It should be like the pict below:
I already check my code, and here it is:
import React from "react";
import './App.css';
import "antd/dist/antd.css";
import { Form, Input, Button } from "antd";
import Operation from "antd/lib/transfer/operation";
import { PlusCircleOutlined } from '#ant-design/icons';
function App() {
return (
<div className="App">
<h2>Dynamic Form Dengan Validasi</h2>
<form>
<Form.Item name={"teacher"} label="Teacher Name">
<Input placeholder="Teacher Name"></Input>
</Form.Item>
<Form.Item name={"class"} label="Class Name">
<Input placeholder="Class"></Input>
</Form.Item>
<Form.List name={"students"}>
{(fields, {add, remove}) => (
<>
{fields.map((field, index)=>{
return (
<Form.Item name={[field.name,"first"]} label={`${index + 1}-Student`}>
<Input placeholder="First Name"></Input>
</Form.Item>
);
})}
<Form.Item>
<Button icon={<PlusCircleOutlined />} type="dashed" block onClick={() => { add();}}>
Add A Student</Button>
</Form.Item>
</>
)}
</Form.List>
</form>
</div>
);
}
export default App;
I don't know what went wrong, only see the warning in the first pict.
You're missing Form.Provider. You need it in order to use Form
import { FormProvider } from 'react-hook-form';
After that make sure to wrap your <Form> tag with a <FormProvider> tag.
function App() {
return (
<div className="App">
<h2>Dynamic Form Dengan Validasi</h2>
<FormProvider>
<Form>
<Form.Item name={"teacher"} label="Teacher Name">
<Input placeholder="Teacher Name"></Input>
</Form.Item>
<Form.Item name={"class"} label="Class Name">
<Input placeholder="Class"></Input>
</Form.Item>
<Form.List name={"students"}>
{(fields, {add, remove}) => (
<>
{fields.map((field, index)=>{
return (
<Form.Item name={[field.name,"first"]} label={`${index + 1}-Student`}>
<Input placeholder="First Name"></Input>
</Form.Item>
);
})}
<Form.Item>
<Button icon={<PlusCircleOutlined />} type="dashed" block onClick={() => { add();}}>
Add A Student
</Button>
</Form.Item>
</>
)}
</Form.List>
</Form>
</FormProvider>
</div>
);
}
Hey guys ı have some issues react hook form handle submit function doesn't work what is issue can you help ?
const AccountTabs = ({ userDetail }) => {
const { register, handleSubmit } = useForm();
console.log(userDetail)
const onSubmit = (data) => {
alert(JSON.stringify(data));
console.log(data)
}
return (
<Fragment>
<Card>
<CardHeader className='border-bottom'>
<CardTitle tag='h4'>İşletme Ayarları</CardTitle>
</CardHeader>
<CardBody className='py-2 my-25'>
<div className='d-flex'>
<div className='me-25'>
<img className='rounded me-50' alt='İşletmeye ait logo ' height='100' width='100' />
</div>
<div className='d-flex align-items-end mt-75 ms-1'>
<div>
<Button tag={Label} className='mb-75 me-75' size='sm' color='primary'>
Yükle
<Input type='file' hidden accept='image/*' />
</Button>
<Button className='mb-75' color='secondary' size='sm' outline >
Sil
</Button>
<p className='mb-0'> JPG veya PNG türünde yükleme yapınız</p>
</div>
</div>
</div>
<Form className='mt-2 pt-50' onSubmit={(e) => { e.preventDefault(); handleSubmit(onSubmit) }} >
<Row>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Ad Soyadı </Label>
<Input defaultValue={userDetail.name} {...register("name", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Kullanıcı adı </Label>
<Input defaultValue={userDetail.username} {...register("kullanici", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > E-mail </Label>
<Input type='email' defaultValue={userDetail.contact.email} {...register("email", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > İşletme Adı </Label>
<Input defaultValue={userDetail.companyName} {...register("companyName", { required: true })} />
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Telefon Numarası </Label>
<Cleave
value={userDetail.contact.phone}
{...register("phone", { required: true })}
className='form-control'
options={{ phone: true, phoneRegionCode: 'TR' }}
/>
</Col>
<Col sm='6' className='mb-1'>
<Label className='form-label' > Adres</Label>
<Input defaultValue={userDetail.contact.address} {...register("address", { required: true })} />
</Col>
<Col className='mt-2' sm='12'>
<input type='submit' className='me-1' value='Kaydet' />
</Col>
</Row>
</Form>
</CardBody>
</Card>
</Fragment>
)
}
export default AccountTabs
form can submit but onSubmit function doesn't work what is problem i am ussed first time react-hook-form library, form can submit but onSubmit function doesn't work what is problem i am ussed first time react-hook-form library,form can submit but onSubmit function doesn't work what is problem i am ussed first time react-hook-form library
handleSubmit fires submit function only when validation is successful, So please see if all the required data is filled when you submit the form ( or handle the validations).
const AccountTabs = ({ userDetail }) => {
const { register, handleSubmit, formState } = useForm();
console.log(userDetail)
const onSubmit = (data) => {
alert(JSON.stringify(data));
console.log(data)
}
// formstate has the errors
console.log(formState.errors);
return (
<Fragment>
//code
</Fragment>
)
}
Check this link for validtions
I am a beginner in reactJS and would like to ask a simple question. I am following some tutorials and I really don't know why this wont work on mine. I know my question is very simple since I am a beginner. Please have a patience with my question.
I have this code from a function component form:
function Login() {
const emailInputRef = useRef();
const passwordInputRef = useRef();
function submitHandler(e) {
e.preventDefault();
const emailInput = emailInputRef.current.value;
const passwordInput = passwordInputRef.current.value;
console.log(emailInput);
}
return (
<>
<Col lg="5" md="7">
<Card className="bg-secondary shadow border-0">
<CardBody className="px-lg-5 py-lg-5">
<div className="text-center text-muted mb-4">
<small>Sign in</small>
</div>
<Form role="form" onSubmit={submitHandler}>
<FormGroup className="mb-3">
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-email-83" />
</InputGroupText>
</InputGroupAddon>
<Input
placeholder="Email"
type="email"
autoComplete="new-email"
ref={emailInputRef}
/>
</InputGroup>
</FormGroup>
<FormGroup>
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-lock-circle-open" />
</InputGroupText>
</InputGroupAddon>
<Input
placeholder="Password"
type="password"
autoComplete="new-password"
ref={passwordInputRef}
/>
</InputGroup>
</FormGroup>
<div className="custom-control custom-control-alternative custom-checkbox">
<input
className="custom-control-input"
id=" customCheckLogin"
type="checkbox"
/>
<label
className="custom-control-label"
htmlFor=" customCheckLogin"
>
<span className="text-muted">Remember me</span>
</label>
</div>
<div className="text-center">
<Button className="my-4" color="primary" type="submit">
Sign in
</Button>
</div>
</Form>
</CardBody>
</Card>
<Row className="mt-3">
<Col xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Forgot password?</small>
</a>
</Col>
<Col className="text-right" xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Create new account</small>
</a>
</Col>
</Row>
</Col>
</>
);
}
I want to bind my input type from my submitHandler and log the values of the input types. I followed a tutorial using refs and I don't know if I made something wrong about it since I was a beginner. When I logged the values it gives me undefined values.
To get the current input reference use innerRef property instead of ref:
<Input
placeholder="Email"
type="email"
autoComplete="new-email"
innerRef={emailInputRef}
/>
const emailInput = emailInputRef.current.value;
ref will only get you a reference to the Input component, innerRef will get you a reference to the DOM input.
You have a few options for that. You can use the useRef React hook or the state stored using the useState React Hook. In both cases you need to import the related hook first. You could use both if you want. You could also use a custom hook with the useReducer React hook.
In your case it would be something like these:
Option # 1: Using useRef
import {useRef} from "react";
function Login() {
const emailInputRef = useRef();
const passwordInputRef = useRef();
function submitFormHandler(event) {
event.preventDefault();
const email = emailInputRef.current.value;
const password = passwordInputRef.current.value;
console.log(`email = ${email} & password = ${password}`);
}
return (
<>
<Col lg="5" md="7">
<Card className="bg-secondary shadow border-0">
<CardBody className="px-lg-5 py-lg-5">
<div className="text-center text-muted mb-4">
<small>Sign in</small>
</div>
<Form role="form" onSubmit={submitFormHandler}>
<FormGroup className="mb-3">
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-email-83"/>
</InputGroupText>
</InputGroupAddon>
<Input
placeholder="Email"
type="email"
id='email'
name='email'
required
autoComplete="new-email"
ref={emailInputRef}
/>
</InputGroup>
</FormGroup>
<FormGroup>
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-lock-circle-open"/>
</InputGroupText>
</InputGroupAddon>
<input
placeholder="Password"
type="password"
id="password"
name="password"
required
autoComplete="new-password"
ref={passwordInputRef}
/>
</InputGroup>
</FormGroup>
<div className="custom-control custom-control-alternative custom-checkbox">
<input
className="custom-control-input"
id=" customCheckLogin"
type="checkbox"
/>
<label
className="custom-control-label"
htmlFor=" customCheckLogin"
>
<span className="text-muted">Remember me</span>
</label>
</div>
<div className="text-center">
<Button className="my-4" color="primary" type="submit">
Sign in
</Button>
</div>
</Form>
</CardBody>
</Card>
<Row className="mt-3">
<Col xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Forgot password?</small>
</a>
</Col>
<Col className="text-right" xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Create new account</small>
</a>
</Col>
</Row>
</Col>
</>
);
};
export default Login;
Option # 2: Using useState
import {useState} from "react";
function Login() {
const [emailState, setEmailState] = useState('');
const [passwordState, setPasswordState] = useState('');
function submitFormHandler(event) {
event.preventDefault();
console.log(`email = ${emailState} & password = ${passwordState}`);
}
const onEmailChangeHandler = (event) => {
setEmailState(event.current.value);
};
const onPasswordChangeHandler = (event) => {
setPasswordState(event.current.value);
};
return (
<>
<Col lg="5" md="7">
<Card className="bg-secondary shadow border-0">
<CardBody className="px-lg-5 py-lg-5">
<div className="text-center text-muted mb-4">
<small>Sign in</small>
</div>
<Form role="form" onSubmit={submitFormHandler}>
<FormGroup className="mb-3">
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-email-83"/>
</InputGroupText>
</InputGroupAddon>
<input
placeholder="Email"
type="email"
id='email'
name='email'
required
autoComplete="new-email"
value={emailState}
onChange={onEmailChangeHandler}
/>
</InputGroup>
</FormGroup>
<FormGroup>
<InputGroup className="input-group-alternative">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="ni ni-lock-circle-open"/>
</InputGroupText>
</InputGroupAddon>
<input
placeholder="Password"
type="password"
id="password"
name="password"
required
autoComplete="new-password"
value={passwordState}
onChange={onPasswordChangeHandler}
/>
</InputGroup>
</FormGroup>
<div className="custom-control custom-control-alternative custom-checkbox">
<input
className="custom-control-input"
id=" customCheckLogin"
type="checkbox"
/>
<label
className="custom-control-label"
htmlFor=" customCheckLogin"
>
<span className="text-muted">Remember me</span>
</label>
</div>
<div className="text-center">
<Button className="my-4" color="primary" type="submit">
Sign in
</Button>
</div>
</Form>
</CardBody>
</Card>
<Row className="mt-3">
<Col xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Forgot password?</small>
</a>
</Col>
<Col className="text-right" xs="6">
<a
className="text-light"
href="#pablo"
onClick={(e) => e.preventDefault()}
>
<small>Create new account</small>
</a>
</Col>
</Row>
</Col>
</>
);
};
export default Login;
Option # 3: Using both React hooks (useRef & useState).
You could use the useRef React hook for focusing purposes only and also use a local state value, using the useState React hook, for the usual purposes of login in.
Option # 4: Using custom hooks.
You can use all the mentioned before, but using primordially a custom hook, which uses the useReducer React hook under the trunk, and then useRef for focusing and useState for other purposes:
Coder example:
Custom hook:
import {useReducer} from "react";
const initialInputState = {
valueState: '',
valueIsTouchedState: false,
};
const inputStateReducer = (state, action) => {
if (action.type === 'SET_VALUE_IS_TOUCHED_STATE') {
return {
valueState: state.valueState,
valueIsTouchedState: action.payload.valueIsTouchedState
};
}
if (action.type === 'SET_VALUE_STATE') {
return {
valueState: action.payload.valueState,
valueIsTouchedState: state.valueIsTouchedState
};
}
return initialInputState;
};
const useInputReducer = (valueValidator) => {
const [inputState, dispatchFunction] = useReducer(inputStateReducer, initialInputState);
const valueIsValidState = valueValidator(inputState.valueState);
const valueInputIsInvalid = (!valueIsValidState && inputState.valueIsTouchedState);
const valueInputChangeHandler = (event) => {
dispatchFunction({type: 'SET_VALUE_IS_TOUCHED_STATE', payload: {valueIsTouchedState: true}});
dispatchFunction({type: 'SET_VALUE_STATE', payload: {valueState: event.target.value}});
};
const valueInputBlurHandler = (event) => {
dispatchFunction({type: 'SET_VALUE_IS_TOUCHED_STATE', payload: {valueIsTouchedState: true}});
// setValueState(event.target.value);
};
const setValueIsTouchedState = (value) => {
dispatchFunction({type: 'SET_VALUE_IS_TOUCHED_STATE', payload: {valueIsTouchedState: value}});
};
const resetValueInput = () => {
dispatchFunction({type: 'SET_VALUE_STATE', payload: {valueState: ''}});
dispatchFunction({type: 'SET_VALUE_IS_TOUCHED_STATE', payload: {valueIsTouchedState: false}});
};
return {
valueState: inputState.valueState,
setValueIsTouchedState,
valueIsValidState,
valueInputIsInvalid,
valueInputChangeHandler,
valueInputBlurHandler,
resetValueInput,
};
};
export default useInputReducer;
Form:
import {Fragment, useRef, useState} from 'react';
import {Prompt} from "react-router-dom";
import useInputReducer from "../../hooks/use-input-reducer";
import * as validators from "../../tools/validators";
import styles from './AuthForm.module.css';
const AuthForm = () => {
const [isLogin, setIsLogin] = useState(true);
const [startedToWork, setStartedToWork] = useState(false);
const {
valueState: emailState,
setValueIsTouchedState: setEmailIsTouchedState,
valueIsValidState: emailIsValidState, valueInputIsInvalid: emailInputIsInvalid,
valueInputChangeHandler: emailInputChangeHandler,
// valueInputBlurHandler: emailInputBlurHandler,
resetValueInput: resetEmailInput,
} = useInputReducer(validators.emailValidator);
const {
valueState: passwordState,
setValueIsTouchedState: setPasswordIsTouchedState,
valueIsValidState: passwordIsValidState, valueInputIsInvalid: passwordInputIsInvalid,
valueInputChangeHandler: passwordInputChangeHandler,
// valueInputBlurHandler: passwordInputBlurHandler,
resetValueInput: resetPasswordInput,
} = useInputReducer(validators.nameValidator);
const formIsValid = (emailIsValidState && passwordIsValidState);
const emailInputRef = useRef();
const passwordInputRef = useRef();
const submitFormHandler = (event) => {
event.preventDefault();
setEmailIsTouchedState(true);
setPasswordIsTouchedState(true);
emailInputRef.current.focus();
if (!formIsValid) {
setProperFocus();
return;
}
console.log('Submitted!. I did something!!');
const email = emailInputRef.current.value;
const password = passwordInputRef.current.value;
resetEmailInput();
resetPasswordInput();
};
const setProperFocus = () => {
if (emailInputIsInvalid) {
emailInputRef.current.focus();
} else if (passwordInputIsInvalid) {
passwordInputRef.current.focus();
}
}
const switchAuthModeHandler = () => {
setIsLogin((prevState) => !prevState);
};
const onStartedToWorkHandler = () => {
setStartedToWork(true);
};
const onFinishEnteringHandler = () => {
setStartedToWork(false);
};
const emailValidityClasses = `${styles.control}${emailInputIsInvalid ? ` ${styles.invalid}` : ''}`;
const passwordValidityClasses = `${styles.control}${passwordInputIsInvalid ? ` ${styles.invalid}` : ''}`;
return (
<Fragment>
<Prompt
when={startedToWork}
message={location =>
`Are you sure you want to go to "${location.pathname}"? \n All your entered data will be lost.`
}
/>
<section className={styles.auth}>
<h1>{isLogin ? 'Login' : 'Sign Up'}</h1>
<form
onSubmit={submitFormHandler}
onChange={onStartedToWorkHandler}
>
<div className={emailValidityClasses}>
<label htmlFor='email'>Your Email</label>
<input
type='email'
id='email'
name='email'
required
autoFocus={true}
ref={emailInputRef}
value={emailState}
onChange={emailInputChangeHandler}
// onBlur={emailInputBlurHandler}
/>
{emailInputIsInvalid ? <p className={styles['error-text']}>The Email must be valid.</p> : <p> </p>}
</div>
<div className={passwordValidityClasses}>
<label htmlFor='password'>Your Password</label>
<input
type='password'
id='password'
required
autoComplete="on"
ref={passwordInputRef}
value={passwordState}
onChange={passwordInputChangeHandler}
// onBlur={passwordInputBlurHandler}
/>
{passwordInputIsInvalid ? <p className={styles['error-text']}>The Password must not be empty.</p> : <p> </p>}
</div>
<div className={styles.actions}>
<button onClick={onFinishEnteringHandler}>{isLogin ? 'Login' : 'Create Account'}</button>
<button
type='button'
className={styles.toggle}
onClick={switchAuthModeHandler}
>
{isLogin ? 'Create new account' : 'Login with existing account'}
</button>
</div>
</form>
</section>
</Fragment>
);
};
export default AuthForm;
I never do react js but i code react native.
I think you can store the input in the state using onChangeText like this
using hooks
const index = ()=>{
const {state,setState} = useState('');
return <TextInput onChangeText={(txt)=>{
setState(txt);
console.log(state); }} />
}
So, this is my App.js file and the next picture is what I get when I hit submit. I want to get all the entered values to be printed on console but that's not happening.
I am also using Flask as backend and I want to get all these data into app.py so how to do that ?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
petalLen: "",
petalWid: "",
sepalLen: "",
sepalWid: "",
};
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event);
for (let [key, value] of data.entries()) {
console.log(key, value);
}
}
render() {
return (
<div className="App">
<h1>Deploy Models for Humans </h1>
<Form>
<Container>
<Row className="Rr">
<Col>
<Form.Label>Petal Length</Form.Label>
<Form.Control
type="text"
name="petalLen"
value={this.state.petalLen}
onChange={this.handleOnChange}
placeholder="Petal Length"
/>
</Col>
<Col>
<Form.Group>
<Form.Label>Petal Width</Form.Label>
<Form.Control
type="text"
name="petalWid"
value={this.state.petalWid}
onChange={this.handleOnChange}
placeholder="Petal Width"
/>
</Form.Group>
</Col>
<Col>
<Form.Group>
<Form.Label>Sepal Length</Form.Label>
<Form.Control
type="text"
name="sepalLen"
value={this.state.sepalLen}
onChange={this.handleOnChange}
placeholder="Sepal Length"
/>
</Form.Group>
</Col>
<Col>
<Form.Group>
<Form.Label>Sepal Width</Form.Label>
<Form.Control
type="text"
name="sepalWid"
value={this.state.sepalWid}
onChange={this.handleOnChange}
placeholder="Sepal Width"
/>
</Form.Group>
</Col>
</Row>
<Button variant="primary" type="submit" onClick={this.handleSubmit}>
Submit
</Button>
</Container>
</Form>
</div>
);
}
}
After I hit submit :
I have two components :
LoginForm which is used to render the form to login in the app
LoginPage which get the data entered in the LoginForm component and send it to a server
For the moment I would like to handle the form submit and the change of an input value. I read these two articles in the react official website to help me :
https://reactjs.org/docs/lifting-state-up.html
https://reactjs.org/docs/forms.html
But I still don't detect the submit and the change from the LoginPage component when I'm entering a value in LoginForm.
Can you help me to see where is my mistake ?
Thanks by advance.
My two components :
LoginPage.js
class LoginPage extends Component {
constructor(props) {
super(props);
this.state = {
login: true, //switch between Login and SignUp
email: '',
password: '',
firstName: '',
lastName: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleSubmit(){
alert("SUBMIT");
}
handleInputChange(event) {
alert("YOUHOU");
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
alert("YEEEP");
}
render(){
return (
<div>
<div>
{this.state.login ?
<Login onSubmit={this.handleSubmit} onChange={this.handleInputChange}/>
:
<Register />
}
</div>
<a
onClick={() => this.setState({ login: !this.state.login })}
>
{this.state.login ? 'Besoin d\'un compte ?' : 'Déjà un compte ?'}
</a>
</div>
)
}
}
LoginForm.js
class LoginForm extends Component {
render(){
return (
<div>
<Card>
<form onSubmit={this.props.handleSubmit}>
<div>
<div>
<TextField name="email" floatingLabelText="Email" errorText="Champ obligatoire" type="text" onChange={this.props.handleInputChange}/>
</div>
<div>
<TextField name="password" floatingLabelText="Mot de passe" errorText="Champ obligatoire" type="password" onChange={this.props.handleInputChange} />
</div>
<CardActions>
<div>
<RaisedButton label="Se connecter" primary={true} type="submit" fullWidth />
</div>
</CardActions>
</div>
</form>
</Card>
</div>
);
}
}
handleInputChange is passed down to LoginForm as onChange prop and similarly handleSubmit is passed down by the name onSubmit and hence you need to use it like
class LoginForm extends Component {
render(){
return (
<div>
<Card>
<form onSubmit={this.props.onSubmit}>
<div>
<div>
<TextField name="email" floatingLabelText="Email" errorText="Champ obligatoire" type="text" onChange={this.props.onChange}/>
</div>
<div>
<TextField name="password" floatingLabelText="Mot de passe" errorText="Champ obligatoire" type="password" onChange={this.props.onChange} />
</div>
<CardActions>
<div>
<RaisedButton label="Se connecter" primary={true} type="submit" fullWidth />
</div>
</CardActions>
</div>
</form>
</Card>
</div>
);
}
}