ReferenceError: fullName is not defined - javascript

I have to create is a registration form that consists of full name, email, password, mobile number, DOB and once the email validation is done and once the submit button is clicked, it should direct me to the login page. The login page has an email and password (the details from registration need not match the login) and once the button is clicked(after the validation) it should display "Welcome". I'm sharing the files here. Used, react-router, Material UI.
Login.js
/* eslint-disable no-undef */
import React, { Component } from "react";
import { Link } from "react-router-dom";
import { Grid, Paper, TextField } from "#material-ui/core";
import { Button } from "#material-ui/core";
import Welcome from './Welcome';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
errors: {},
};
this.validate = this.validate.bind(this);
}
validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
validate() {
const { email, password, errors } = this.state;
if (!this.validateEmail(email)) {
errors.email = "Provide valid email";
}
if (password.length > 5) {
errors.password = "Provide min 5-digit password";
}
if (errors) {
this.setState({ errors });
} else {
this.props.location.push('/Welcome');
}
}
render() {
const paperStyle = {
padding: 20,
height: "70vh",
width: 280,
margin: "20px auto",
};
return (
<Grid>
<Paper elevation={10} style={paperStyle}>
<Grid align="center">
<h2>Login</h2>
</Grid>
<TextField
error={errors.email}
label="Email"
placeholder="Enter mail"
fullwidth
value={email}
onChange={(e) => this.setState({ email: e.target.value })}
required
helperText={errors.password}
/>
<TextField
error={errors.password}
label="Password"
placeholder="Enter password"
type="password"
fullwidth
required
value={password}
onChange={(e) => this.setState({ password: e.target.value })}
helperText={errors.password}
/>
{/*<Link to="/Welcome">*/}
<Button variant="contained" color="primary" onClick={this.validate}>
Login
</Button>
{/*</Link> */}
</Paper>
</Grid>
);
}
}
export default Login;
Registration.js
/* eslint-disable no-undef */
import React, { Component} from 'react';
import { Link } from "react-router-dom";
import { Grid, Paper, TextField } from "#material-ui/core";
import { Button } from "#material-ui/core";
import Login from './Login';
class Registration extends Component {
constructor(props) {
super(props);
this.state = {
fullName: "",
mobileNumber: "",
email: "",
password: "",
errors: {},
};
this.validate = this.validate.bind(this);
}
validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
validate() {
const { fullName, email, password, errors } = this.state;
if (!this.validateEmail(email)){
errors.email = "Provide valid email";
}
if (password.length > 5){
errors.password = "Provide min 5-digit password";
}
if (errors) {
this.setState({ errors });
} else {
this.props.location.push('/Login');
}
}
render() {
const paperStyle = {
padding: 20,
height: "70vh",
width: 280,
margin: "20px auto",
};
return (
<Grid>
<Paper elevation={10} style={paperStyle}>
<Grid align="center">
<h2>Login</h2>
</Grid>
<TextField
label="Full name"
placeholder="Enter name"
fullwidth
value={fullName}
onChange={(e) => this.setState({ fullName: e.target.value })}
required
helperText={errors.fullName}
/>
<TextField
type = 'number'
label="Mobile number"
placeholder="Enter mobile number"
fullwidth
// eslint-disable-next-line no-undef
value={mobileNumber}
onChange={(e) => this.setState({ mobileNumber: e.target.value })}
required
helperText={errors.mobileNumber}
/>
<TextField
error={errors.email}
label="Email"
placeholder="Enter mail"
fullwidth
value={email}
onChange={(e) => this.setState({ email: e.target.value })}
required
helperText={errors.email}
/>
<TextField
error={errors.password}
label="Password"
placeholder="Enter password"
type="password"
fullwidth
required
value={password}
onChange={(e) => this.setState({ password: e.target.value })}
helperText={errors.password}
/>
{/*<Link to="/Login">*/}
<Button variant="contained" color="primary" onClick={this.validate}>
Register here
</Button>
{/*</Link>*/}
</Paper>
</Grid>
);
}
}
export default Registration;
App.js
import React, { Component } from "react";
import "./App.css";
import Login from "./Login";
import Registration from "./Registration";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Welcome from "./Welcome";
import { Typography } from "#material-ui/core";
class App extends Component {
render() {
return (
<Router>
<Typography>
<div className="App">
<Switch>
<Route path="/" exact component={Registration} />
<Route path="/Login" component={Login} />
<Route path="/Welcome" component={Welcome} />
</Switch>
</div>
</Typography>
</Router>
);
}
}
export default App;
Welcome js
import React from "react";
function Welcome() {
return <h1>Welcome</h1>;
}
export default Welcome;

You need add const { fullName, email, password, errors } = this.state; in the render and before return

Related

Why won't my axios request return the proper data?

I have an api running at the url used in my axios instance. A route is defined for login that returns JWT access and refresh tokens if valid credentials are provided. I can test it using postman and everything works great, but in my app using axios no tokens or error gets returned even with valid credentials. The API is setup for cors also and is running live.
here is the axios instance:
import axios from 'axios';
const url = NOT SHOWN;
const axiosInstance = axios.create({
baseURL: url,
headers: {
'Content-Type': 'application/json',
},
});
export default axiosInstance;
here is the basic login component:
import React, { Component } from 'react';
import { Link as RouteLink, Redirect } from 'react-router-dom';
import axiosInstance from '../../axiosInstance';
//material ui
import Button from '#material-ui/core/Button';
import CssBaseline from '#material-ui/core/CssBaseline';
import TextField from '#material-ui/core/TextField';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import Checkbox from '#material-ui/core/Checkbox';
import Link from '#material-ui/core/Link';
import Grid from '#material-ui/core/Grid';
import Typography from '#material-ui/core/Typography';
import { makeStyles } from '#material-ui/core/styles';
import Container from '#material-ui/core/Container';
class Login extends Component {
state = {
email: '',
password: '',
isAuthenticated: false,
};
login(email, password) {
const data = {
email: email,
password: password,
};
axiosInstance
.post('/login', data)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
}
onSubmit = (e) => {
const { email, password } = this.state;
this.login(email, password);
};
onChange = (e) => this.setState({ [e.target.name]: e.target.value.trim() });
render() {
if (this.state.isAuthenticated) {
return <Redirect to='/' />;
}
return (
<Container component='main' maxWidth='xs' style={{ marginTop: '75px' }}>
<CssBaseline />
<div>
<Typography component='h1' variant='h3' align='center'>
Login
</Typography>
<form noValidate>
<TextField
variant='outlined'
margin='normal'
required
fullWidth
id='email'
label='Email Address'
name='email'
autoComplete='email'
autoFocus
onChange={this.onChange}
/>
<TextField
variant='outlined'
margin='normal'
required
fullWidth
name='password'
label='Password'
type='password'
id='password'
autoComplete='current-password'
onChange={this.onChange}
/>
<FormControlLabel
control={<Checkbox value='remember' color='primary' />}
label='Remember me'
/>
<Button
type='submit'
fullWidth
variant='contained'
color='primary'
//className={classes.submit}
onClick={this.onSubmit}
>
LOGIN
</Button>
<Grid container>
<Grid item xs>
<Link variant='body2'>Forgot password?</Link>
</Grid>
<Grid item>
<Link component={RouteLink} to={'/signup'} variant='body2'>
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
</Container>
);
}
}
export default Login;
'''
I believe the login function is not defined properly so it is not being called. Please try using a function expression:
login = (email, password) => {
const data = {
email: email,
password: password,
};
axiosInstance
.post('/login', data)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
}
onSubmit = (e) => {
const { email, password } = this.state;
login(email, password);
};

How to validate username and password for my form?

I have created a form with two field username and password and both are number username has length of 3 and password has a length of 6 .Could someone help me with validation.Such that if user enter a username of length less than 3 it should show a message and if somone shows password less than or greater than 6 it should show a message
import withRoot from './modules/withRoot';
// --- Post bootstrap -----
import React, { useState } from 'react';
import history from './history';
import { makeStyles } from '#material-ui/core/styles';
import Grid from '#material-ui/core/Grid';
import Link from '#material-ui/core/Link';
import { FormGroup, FormControl, ControlLabel } from "react-bootstrap";
import { Field } from 'react-final-form';
import Typography from './modules/components/Typography';
import AppFooter from './modules/views/AppFooter';
import AppAppBar from './modules/views/AppAppBar';
import Axios from 'axios';
import AppForm from './modules/views/AppForm';
import Button from '#material-ui/core/Button';
import { Alert } from 'react-bootstrap';
import { email, required } from './modules/form/validation';
import RFTextField from './modules/form/RFTextField';
import FormButton from './modules/form/FormButton';
import FormFeedback from './modules/form/FormFeedback';
import TextField from '#material-ui/core/TextField';
import Home from './Home';
import Dashb from './Dashb';
const useStyles = makeStyles((theme) => ({
form: {
marginTop: theme.spacing(6),
},
button: {
marginTop: theme.spacing(3),
marginBottom: theme.spacing(2),
},
feedback: {
marginTop: theme.spacing(2),
},
}));
export default function SignIn() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [status, setStatus] = useState(true);
const classes = useStyles();
let demo;
function validateForm() {
return username.length > 0 && password.length > 0;
}
function setIncorrect() {
setStatus(false);
}
function setCorrect() {
setStatus(true);
}
async function handleSubmit(event) {
event.preventDefault()
let user = await Axios.get(
'http://localhost:9000/admin-service/admin/check/' +
username +
'/' +
password
)
.then(response => {
demo = response.data
if (demo == true) {
history.push('/admin');
console.log('####')
} else{
console.log('not true')
Functions();
}
})
.catch(error => {
console.log(error.response.data)
setIncorrect()
})
}
function Functions() {
alert("PLEASE ENTER CORRECT CREDENTIALS!!!!!!!!!!")
}
return (
<React.Fragment>
<AppAppBar />
<AppForm>
<React.Fragment>
<Typography variant="h3" gutterBottom marked="center" align="center">
Admin Sign In
</Typography>
</React.Fragment>
<form onSubmit={handleSubmit} className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="username"
label="Username"
name="username"
autoFocus
onChange={e => { setUsername(e.target.value); setCorrect() }}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
onChange={e => { setPassword(e.target.value); setCorrect() }}
/>
{(!status) && <Alert severity="error">Incorrect credentials. Please try again</Alert>}
<FormButton
type="submit"
className={classes.button}
disabled={!validateForm()}
size="large"
color="secondary"
fullWidth
>
Sign In
</FormButton>
</form>
<Typography align="center">
<Link underline="always" href="/premium-themes/onepirate/forgot-password/">
Forgot password?
</Link>
</Typography>
</AppForm>
</React.Fragment>
);
}
Create two new states: usernameIsValid & passwordIsValid with initial state set to 'true'
On calling handleSubmit(), before calling the api create a condition as follows:
if (username.length !== 3) setUsernameIsValid(false)
if (password.length !== 3) setPasswordIsValid(false)
If the condition fails, do not make the api call.
Under the TextFields create a div to contain the error like so:
{!userNameIsValid && <div>Please enter a valid username</div>}

Validation for from in recatjs is not happenig?

I have tried making the username and possword field validated but it by default setting "username is incorrect" when the page loads but it should happen only after user types and then the error should be shown respectively. So once user enters the username and if length is less than "3" a message should be display below the respective fild "Username should be 3 digit!!!"
import withRoot from './modules/withRoot';
// --- Post bootstrap -----
import React, { useState } from 'react';
import history from './history';
import { makeStyles } from '#material-ui/core/styles';
import Grid from '#material-ui/core/Grid';
import Link from '#material-ui/core/Link';
import {BrowserRouter as Router, Route} from 'react-router-dom'
import { FormGroup, FormControl, ControlLabel } from "react-bootstrap";
import { Field } from 'react-final-form';
import Typography from './modules/components/Typography';
import AppFooter from './modules/views/AppFooter';
import AppAppBar from './modules/views/AppAppBar';
import Axios from 'axios';
import AppForm from './modules/views/AppForm';
import Button from '#material-ui/core/Button';
import { Alert } from 'react-bootstrap';
import { email, required } from './modules/form/validation';
import RFTextField from './modules/form/RFTextField';
import FormButton from './modules/form/FormButton';
import FormFeedback from './modules/form/FormFeedback';
import TextField from '#material-ui/core/TextField';
import Home from './Home';
import Dashb from './Dashb';
import Admin from './Admin';
const useStyles = makeStyles((theme) => ({
form: {
marginTop: theme.spacing(6),
},
button: {
marginTop: theme.spacing(3),
marginBottom: theme.spacing(2),
},
feedback: {
marginTop: theme.spacing(2),
},
}));
const SignIn = (props) => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [usernameerror, setUsernameerror] = useState("");
const [passworderror, setPassworderror] = useState("");
const [status, setStatus] = useState(true);
const classes = useStyles();
let demo;
function validateForm() {
if(username.length!=3)
{
return("Wrong username");
}
if(password.length!=6 )
{
return("Wrong password")
}
return 1;
}
function setIncorrect() {
setStatus(false);
}
function setCorrect() {
setStatus(true);
}
function validate(){
let usernameerror ="";
let passworderror = "";
if(username.length==3){
usernameerror = 'invalid username';
}
if (usernameerror){
setUsernameerror({usernameerror});
return false;
}
}
const handleSubmit = (event) => {
event.preventDefault()
let user = Axios.get(
'http://localhost:9000/admin-service/admin/check/' +
username +
'/' +
password
)
.then(response => {
demo = response.data
if (demo == true) {
props.history.push({
pathname: '/admin',
username
});
console.log('####')
} else{
console.log('not true')
Functions();
}
})
.catch(error => {
console.log(error.response.data)
setIncorrect()
})
};
function Functions() {
alert("PLEASE ENTER CORRECT CREDENTIALS!!!!!!!!!!")
}
return (
<React.Fragment>
<AppAppBar />
<AppForm>
<React.Fragment>
<Typography variant="h3" gutterBottom marked="center" align="center">
Admin Sign In
</Typography>
</React.Fragment>
<form onSubmit={handleSubmit} className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="username"
label="Admin-Id"
name="username"
autoFocus
onChange={e => { setUsername(e.target.value); setCorrect() }}
/>
<div style={{ fontSize: 11, color: "red"}}>
{validateForm()}
</div>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
onChange={e => { setPassword(e.target.value); setCorrect() }}
/>
<div style={{ fontSize: 11, color: "red"}}>
{validateForm()}
</div>
{(!status) && <Alert severity="error">Incorrect credentials. Please try again</Alert>}
<FormButton
type="submit"
className={classes.button}
//disabled={!validateForm()}
size="large"
color="secondary"
fullWidth
>
Sign In
</FormButton>
</form>
<Typography align="center">
<Link underline="always" href="/premium-themes/onepirate/forgot-password/">
Forgot password?
</Link>
<p>NOTE-PASSWORD IS YOUR USER PIN</p>
</Typography>
</AppForm>
</React.Fragment>
);
}
export default SignIn;
Try this in your validate form function.The conditions were not working in this respective form
function validateForm() {
if(username.length===0)
{
return null
}
else if(password.length===0 )
{
return null
}
else if(username.length<3)
{
return("Username must be 3 chars long");
}
else if(password.length<6 )
{
return("Password must be 6 chars long")
}
}

can I create a custom route without using redux?

I have a Loginscreen.js
import React, { Component } from 'react';
import Login from './Login';
class Loginscreen extends Component {
constructor(props){
super(props);
this.state={
username:'',
password:'',
loginscreen:[],
loginmessage:'',
isLogin:true
}
}
componentWillMount(){
var loginscreen=[];
loginscreen.push(<Login parentContext={this} appContext={this.props.parentContext}/>);
this.setState({
loginscreen:loginscreen
})
}
render() {
return (
<div className="loginscreen">
{this.state.loginscreen}
</div>
);
}
}
const style = {
margin: 15,
};
export default Loginscreen;
and I have Login.js
import React, { Component } from 'react';
import { Button, Form, Grid, Segment } from 'semantic-ui-react'
import axios from 'axios';
import validator from 'Validator';
import InlineError from './components/messages/InlineError';
import UploadScreen from './UploadScreen';
import { BrowserRouter as Router, Route } from 'react-router-dom';
class Login extends Component {
constructor(){
super();
this.state={
email:'',
password:'',
errors: {}
}
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
validate = () => {
if (!this.state.password) this.state.errors.password = "Can't be blank";
if (!this.state.email) this.state.errors.email = "Invalid Email";
return this.state.errors;
}
onSubmit = (e) => {
const errors = this.validate(this.state);
this.setState({ errors });
e.preventDefault();
var apiBaseUrl = "http://127.0.0.1:8000/api/auth/login";
var self = this;
var payload={
"email":this.state.email,
"password":this.state.password
}
var config = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
withCredentials: false
}
axios.post(apiBaseUrl, payload, config)
.then(function (response) {
console.log(response);
if(response.status == 200){
console.log("Login successful");
}
else if(response.status == 204){
console.log("Username password do not match");
alert("username password do not match")
}
else{
console.log("Username does not exists");
alert("Username does not exist");
}
})
.catch(function (error) {
console.log(error);
});
}
render() {
const { email, password, errors } = this.state;
return (
<div className='login-form'>
<style>{`
body > div,
body > div > div,
body > div > div > div.login-form {
height: 100%;
}
`}</style>
<Grid textAlign='center' style={{ height: '100%' }} verticalAlign='middle'>
<Grid.Column style={{ maxWidth: 450 }}>
<br />
<br />
<Form size='large' onSubmit={this.onSubmit}>
<Segment stacked>
<Form.Input
type='text'
name='email'
value={email}
onChange={this.onChange}
fluid
icon='user'
iconPosition='left'
placeholder='E-mail address'
/>
{ errors.email && <InlineError text={errors.email} />}
<Form.Input
type='password'
name='password'
value={password}
onChange={this.onChange}
fluid
icon='lock'
iconPosition='left'
placeholder='Password'
/>
{ errors.password && <InlineError text={errors.password} />}
<Button fluid size='large' type="submit">
Login
</Button>
</Segment>
</Form>
</Grid.Column>
</Grid>
</div>
);
}
}
const style = {
margin: 15,
};
export default Login;
that returns:
can I use this response alone to be able to create a conditional statement that would create a custom route that can only be accessed if someone is logged in successfully?
this is my app.js
import React from 'react';
import { Route } from 'react-router-dom';
import LoginPage from "./Login";
import UploadScreen from "./UploadScreen";
const App = () => (
<div className="ui container">
<Route path="/" exact component={LoginPage} />
<Route path="/upload" exact component={UploadScreen} />
</div>
);
export default App;
I want that "/upload" route to only be accessible if someone is logged in. can I do that?
Here's a way to make public and private routes:
const PrivateRoute = ({ component: Component, ...rest, loggedIn }) => (
<Route
{...rest}
render={props =>
(loggedIn ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: LOGIN,
state: { from: props.location },
}}
/>
))
}
/>
);
const PublicRoute = ({ component: Component, ...rest, loggedIn}) => (
<Route
{...rest}
render={props =>
(!loggedIn ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: HOME,
state: { from: props.location },
}}
/>
))
}
/>
)

redux-form onSubmit refreshes page

I am new to redux-form and I'm having a strange issue with handling onSubmit.
When I set up my project exactly as in the redux-form example here http://redux-form.com/6.7.0/examples/syncValidation/ it works as expected. I have attempted to extend this example for my needs and have confirmed that it works as expected when it loads the form like so: route component > form.
The issue arises when I attempt to load the form within a react component which is loaded via a route (route component > container component > form). When I click submit the field values are added to the address bar and form validation doesn't run. I have tried absolutely everything I can think of to fix this. The code provided below will work correctly if you replace <Main /> with <RegisterForm handleSubmit={showResults} /> in index.js. Any ideas where I'm going wrong here?
RegisterForm.js:
import React from 'react';
import { Field, reduxForm } from 'redux-form';
const validate = values => {
const errors = {};
if (!values.name) {
errors.name = 'Required';
} else if (values.name.length <= 2) {
errors.username = 'Must be 2 characters or more';
} else if (values.name.length > 50) {
errors.username = 'Must be 50 characters or less';
}
if (!values.email) {
errors.email = 'Required';
} else if (!/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z] {2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address';
}
if (!values.password) {
errors.password = 'Required';
} else if (!values.confirm) {
errors.confirm = 'Required';
} else if (values.password !== values.confirm) {
errors.confirm = 'Passwords do not match';
}
return errors;
};
const renderField = ({ input, label, type, id, meta: { touched, error, warning } }) => (
<div>
<label htmlFor={id}>{label}</label>
<div>
<input {...input} id={id} placeholder={label} type={type} />
{touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
</div>
</div>
);
const RegisterForm = (props) => {
const { handleSubmit, pristine, reset, submitting } = props
return (
<form onSubmit={handleSubmit}>
<div className="row">
<div className="medium-6 columns medium-centered">
<Field type="text" id="name" name="name" component={renderField} placeholder="name" label="Name" />
</div>
<div className="medium-6 columns medium-centered">
<Field type="text" id="email" name="email" component={renderField} placeholder="email" label="Email" />
</div>
<div className="medium-6 columns medium-centered">
<Field type="password" id="password" name="password" component={renderField} placeholder="password" label="Password" />
</div>
<div className="medium-6 columns medium-centered">
<Field type="password" id="confirm" name="confirm" component={renderField} placeholder="confirm" label="Confirm password" />
</div>
<div className="medium-6 columns medium-centered">
<button type="submit" disabled={submitting}>Submit</button>
</div>
</div>
</form>
);
};
export default reduxForm({
form: 'register', // a unique identifier for this form
validate,
})(RegisterForm);
Index.js(works):
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { HashRouter as Router, hashHistory } from 'react-router-dom';
const store = require('./store').configure();
import RegisterForm from './RegisterForm.jsx';
import Main from './Main.jsx';
const rootEl = document.getElementById('app');
const showResults = (values) => {
window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
}
ReactDOM.render(
<Provider store={store}>
<Router history={hashHistory}>
<div style={{ padding: 15 }}>
<h2>Synchronous Validation</h2>
<RegisterForm handleSubmit={showResults} />
</div>
</Router>
</Provider>,
rootEl,
);
Index.js(doesn't work):
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { HashRouter as Router, hashHistory } from 'react-router-dom';
const store = require('./store').configure();
import RegisterForm from './RegisterForm.jsx';
import Main from './Main.jsx';
const rootEl = document.getElementById('app');
const showResults = (values) => {
window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
}
ReactDOM.render(
<Provider store={store}>
<Router history={hashHistory}>
<div style={{ padding: 15 }}>
<h2>Synchronous Validation</h2>
<Main />
</div>
</Router>
</Provider>,
rootEl,
);
Main.js:
import React, { Component } from 'react';
import RegisterForm from './RegisterForm.jsx';
const showResults = (values) => {
window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`);
};
class Register extends Component {
render() {
return (
<RegisterForm handleSubmit={showResults} />
);
}
}
export default Register;
You should pass in your submit handler to the onSubmit prop, not handleSubmit. It comes in to your form component as handleSubmit, so that code should be fine.
class Register extends Component {
render() {
return (
//change this
<RegisterForm onSubmit={showResults} />
);
}
}

Categories