Add alert upon form submission in reactjs - reactjs

I am having the hardest time trying to get an alert to pop up after clicking on a button. I have been working on it for quite a while but can't seem to figure out where I am wrong. As per the code below, everything works fine, but the Alert will not show up. Any suggestions or advice would be greatly appreciated.
import React, {useState} from 'react';
import { Redirect } from 'react-router-dom'
import { MDBContainer, MDBRow, MDBCol, MDBBtn, MDBIcon } from 'mdbreact';
import NavBar from "./NavBar";
import Footer from "./Footer";
import emailjs from 'emailjs-com';
import{ init } from 'emailjs-com';
function Contact() {
const [alertVisibility , setAlertVisibility ] = useState(false)
function sendEmail(e) {
e.preventDefault();
emailjs.sendForm('hidden', 'hidden', e.target, 'hidden')
.then((result) => {
setAlertVisibility(true);
if (setAlertVisibility === true ) {
return(
<button class="closebtn">
Great, your message has been sent.</button>
)
}
});
e.target.reset();
};
return (
<div>
<NavBar />
<br />
<br />
<br />
<br />
<br />
<MDBContainer>
<MDBRow className = "formcontainer">
<MDBCol md="6">
<form onSubmit={sendEmail}>
<p className="h4 text-center mb-4">Fill in the information below to contact me!</p>
<br />
<label htmlFor="defaultFormContactNameEx" className="grey-text" > Your name </label>
<input required type="text" id="defaultFormContactNameEx" className="form-control" name="user_name" />
<br />
<label htmlFor="defaultFormContactEmailEx" className="grey-text"> Your email </label>
<input required type="email" id="defaultFormContactEmailEx" className="form-control" name="user_email"/>
<br />
<label htmlFor="defaultFormContactSubjectEx" className="grey-text"> Subject</label>
<input required type="text" id="defaultFormContactSubjectEx" className="form-control" name="user_subject" />
<br />
<label htmlFor="defaultFormContactMessageEx" className="grey-text"> Your message </label>
<textarea required type="text" id="defaultFormContactMessageEx" className="form-control" rows="7" name="message"/>
<div className="text-center mt-4">
<MDBBtn color="warning" outline type="submit">
Send
<MDBIcon far icon="paper-plane" className="ml-2" />
</MDBBtn>
</div>
</form>
</MDBCol>
</MDBRow>
</MDBContainer>
<br />
<br />
<Footer />
</div>
);
};
export default Contact;

You are updating alertVisibility with the useState function, so your check should be for
if (alertVisibility === true) {...

You can use
SweetAlert2
import React, {useState} from 'react';
import { Redirect } from 'react-router-dom'
import { MDBContainer, MDBRow, MDBCol, MDBBtn, MDBIcon } from 'mdbreact';
import NavBar from "./NavBar";
import Footer from "./Footer";
import emailjs from 'emailjs-com';
import{ init } from 'emailjs-com';
import Swal from 'sweetalert2';
function Contact() {
const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
emailjs
.sendForm(
EMAILJS_SERVICE_ID,
EMAILJS_TEMPLATE_ID,
form.current,
EMAILJS_PUBLIC_KEY
)
.then(
(result) => {
Swal.fire({
icon:"success",
title:`<h5 style='color:green'>Message Sent Successfully</h5>`,
confirmButtonColor: 'green',
})
},
(error) => {
Swal.fire({
icon:"error",
title:`<h5 style='color:red'>Ooops, something went wrong</h5>`,
confirmButtonColor: 'red',
})
}
);
e.target.reset()
};
return(
<div>
</div>
)
}
export default Contact;

Related

Using useEffect in react js to sent google rechaptha token

Hi i want implementation google rechapta using react, this is my react code
import { useForm } from 'react-hook-form';
import { useHistory } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import swal from 'sweetalert';
import ReCAPTCHA from "react-google-recaptcha";
const ContactForm = (props) => {
const {submitBtnClass } = props;
const { register, handleSubmit } = useForm();
const [token, setToken] = useState();
const history=useHistory();
const recaptchaRef = React.useRef();
function onChange(value) {
console.log("Captcha value:", value);
setToken(value);
}
useEffect(()=>{
document.getElementById("contact_tokenVal").value = token;
//const value = props.value
//setToken(value)
},[token]);
const onSubmit = data_api => {
axios
.post('http://localhost/erlanggastudio-rest-api/contact.php',data_api)
.then(res=>{
console.log(data_api);
history.push('/onepage-3');
swal(res.data.title, res.data.text, res.data.icon);
})
.catch(err => {
console.log(err);
});
};
return (
<form id="contact-form" onSubmit={handleSubmit(onSubmit)}>
<div className="row">
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_name" name="contact_name" placeholder="Nama" {...register('contact_name')} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_email" name="contact_email" placeholder="E-Mail" {...register('contact_email')} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_mobilephone" name="contact_mobilephone" placeholder="No Telepon" {...register('contact_mobilephone')} required/>
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_website" name="contact_website" placeholder="Website Anda" {...register('contact_website')} />
</div>
<div className="col-12 mb-30">
<textarea className="from-control" id="contact_message" name="contact_message" placeholder="Isi Pesan" {...register('contact_message')} required ></textarea>
</div>
<div className="col-12 mb-30">
<input className="from-control" type="hidden" id="contact_serverKey" name="contact_serverKey" value="6Lea50IhAAAAAAtfj-sElz7biY8WlDgrNwy7M7Tx" {...register('contact_serverKey')} />
<input className="from-control" type="hidden" id="contact_siteKey" name="contact_siteKey" value="6Lea50IhAAAAAEgdIvB6xUJ8KJCUyO-xKpPnA0fO" {...register('contact_siteKey')} />
<textarea className="from-control" id="contact_tokenVal" name="contact_tokenVal" defaultValue={token} {...register('contact_tokenVal')} />
</div>
<div className="col-md-6 mb-30">
<ReCAPTCHA
ref={recaptchaRef}
sitekey="6Lea50IhAAAAAEgdIvB6xUJ8KJCUyO-xKpPnA0fO"
onChange={onChange}
/>
</div>
</div>
<div className="btn-part">
<button className={submitBtnClass ? submitBtnClass : 'readon learn-more submit'} type="submit">Kirim</button>
</div>
</form>
);
}
export default ContactForm;
when the code running the view is like this :
i want to sent rechapta token using
<textarea className="from-control" id="contact_tokenVal" name="contact_tokenVal" defaultValue={token} {...register('contact_tokenVal')} />
after user klik rechapta, end will sent to server using axios, but i have some problem when sent the data to API Server using axion the rechapta token is blank like this screenshot :
my question is how to sent the rechapta token?, i'm using document.getElementById in useEffect, but still the value after sent is blank

Change auth state from custom component while using #aws-amplify with react

I am trying to integrate Amplify Auth with a React application.
I am using AmplifyAuthenticator from #aws-amplify/ui-react package to customize the auth flow.
Though I can use AmplifySignIn component and customize it, I want to create a totally custom instead of AmplifySignIn.
Following is what my custom component looks like:
import React from 'react';
import { Auth } from 'aws-amplify';
import { useForm } from "react-hook-form";
export default function CustomSignIn(props){
const { register, reset, errors, handleSubmit } = useForm();
const onSubmit = async data => {
await Auth.signIn(data.username, data.password);
};
return(
<form className="mt-5" onSubmit={handleSubmit(onSubmit)} slot={props.slot}>
<h4>Login</h4>
<p>Need an account? <span>Create an account</span></p>
<div className="form-group">
<label>Email address</label>
<input type="username" name="username" className="form-control" ref={register({required: true})}/>
</div>
<div className="form-group">
<label>Password</label>
<input type="password" name="password" className="form-control" ref={register({required: true})}/>
</div>
<button type="submit" class="btn btn-primary btn-block">Continue</button>
</form>
);
}
Following is how I am trying to manage auth state:
import React, {useEffect} from 'react';
import { AmplifyAuthenticator } from '#aws-amplify/ui-react';
import '../styles/App.scss';
import { AuthState, onAuthUIStateChange } from '#aws-amplify/ui-components';
import ProtectedRoutes from './ProtectedRoutes';
import logo from '../assets/logo.svg';
import CustomSignIn from '../modules/auth/CustomSignIn';
function App() {
const [authState, setAuthState] = React.useState();
const [user, setUser] = React.useState();
useEffect(() => {
return onAuthUIStateChange((nextAuthState, authData) => {
setAuthState(nextAuthState);
setUser(authData)
});
}, []);
return ( authState === AuthState.SignedIn && user )
?
(
<ProtectedRoutes />
)
:
(
<div className="container-fluid container-fluid--auth">
<div className="row">
<div className="col-md-8">
<div className="row">
<div className="col-12 py-3">
<img className="logo" src={logo} alt="logo" />
</div>
</div>
<div className="row">
<div className="col-md-4 offset-md-4">
<AmplifyAuthenticator>
<CustomSignIn slot="sign-in" />
</AmplifyAuthenticator>
</div>
</div>
</div>
<div className="col-md-4 col--auth-sidebar">
</div>
</div>
</div>
);
}
export default App;
The thing is, how do I take the user to the Sign Up page when the user clicks on the "Create an account" button on the Sign In page?

Inputting an ARRAY into a FORM field in REACT

I am trying to learn to code by following an eCommerce product tutorial guide in React.
I have finished setting up the product page and checkout.
My goal now is to extract the cart: [] along with the checkout total into a form using EmailJS.
import React from 'react';
import emailjs from 'emailjs-com';
import './form.css';
import { ProductConsumer } from '../../context'
import CartList from './CartList'
import CartColumns from "./CartColumns"
import CartTotals from './CartTotals'
import Title from "../Title";
import { ProductProvider } from "../../context"
import CartItem from './CartItem'
export default function CheckOut() {
function sendEmail(e) {
alert("Your order has been placed!")
e.preventDefault();
emailjs.sendForm('gmail', 'template_3DAGPnwJ', e.target, 'user_m49ol85bvoqFluF8IKatG')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
}
let Order = "cat"
return (
<div>
<ProductConsumer>
{value => {
return(
<div>
<Title name="Check" title="Out"/>
<CartColumns />
<CartList value={value} />
<CartTotals value={value}/>
</div>
)
}
}
</ProductConsumer>
<form className="contact-form" onSubmit={sendEmail}>
<label>Contact Number eg. 12345678 </label>
<input type="tel" name="contact_number" placeholder="12345678" pattern="[0-9]{8}" required />
<label>Name</label>
<input type="name" name="user_name" required />
<label>Email</label>
<input type="email" name="user_email" required />
<label>Address Line 1</label>
<input type="address-line1" name="user_address1" required />
<label>Address Line 2</label>
<input type="address-line2" name="user_address2" />
<label>Message (eg. Special Requests)</label>
<textarea name="message_html" />
<input type="submit" value="Place Order" />
<textarea name="proudct order" value={Order}/>
</form>
</div>
);
}
So far the textarea is showing "cat" from the let Order = "cat".
I would like to put the array information from CartList and CartTotal into Order. Once the client submits the form, I will have their name email address and the order they collected in the cart. This will be emailed to me via EmailJS.
import React from 'react';
import emailjs from 'emailjs-com';
import './form.css';
import { ProductConsumer } from '../../context';
import CartList from './CartList';
import CartTotals from './CartTotals';
import Title from '../Title';
export default function CheckOut() {
function sendEmail(e) {
alert('Your order has been placed! Our staff will get in touch with you to confirm your order and to process payment.');
e.preventDefault();
emailjs
.sendForm(
'gmail',
'xxxxxxxxx',
e.target,
'xxxxxxxxx'
)
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
}
const Form = ({ context }) => {
let Order = context.cart.map((item) => `ID: ${item.id} \n${item.title} \t $ ${item.price} \t Qty:${item.count} \n\n`);
let OrderSubtotal = context.cartSubtotal ;
let OrderServce = context.cartService;
let OrderShipping = context.cartShipping;
let OrderTotal = context.cartTotal;
return (
<form className="contact-form" onSubmit={sendEmail}>
<label>Contact Number eg. 12345678 </label>
<input
type="tel"
name="contact_number"
placeholder="12345678"
pattern="[0-9]{8}"
required
/>
<label>Name</label>
<input type="name" name="user_name" required />
<label>Email</label>
<input type="email" name="user_email" required />
<label>Address Line 1</label>
<input type="address-line1" name="user_address1" required />
<label>Address Line 2</label>
<input type="address-line2" name="user_address2" />
<label>Message (eg. Special Requests)</label>
<textarea name="message_html" />
<input type="submit" value="Place Order" />
<textarea style={{display:"none"}} name="Order" defaultValue={Order} />
<textarea style={{display:"none"}} name="OrderSubtotal" defaultValue={OrderSubtotal} />
<textarea style={{display:"none"}} name="OrderServce" defaultValue={OrderServce} />
<textarea style={{display:"none"}} name="OrderShipping" defaultValue={OrderShipping} />
<textarea style={{display:"none"}} name="OrderTotal" defaultValue={OrderTotal} />
</form>
);
};
return (
<div>
<ProductConsumer>
{(value) => {
return (
<div>
<Title name="Check" title="Out" />
<CartList value={value} />
<CartTotals value={value} />
</div>
);
}}
</ProductConsumer>
<ProductConsumer>
{(context) => <Form context={context} />}
</ProductConsumer>
</div>
);
}
The answer.
import { ProductConsumer } from '../../context';
let Order = context.cart.map((item) => ID: ${item.id} \n${item.title} \t $ ${item.price} \t Qty:${item.count} \n\n);
which is then exported to emailJS in the textarea.
<textarea style={{display:"none"}} name="Order" defaultValue={Order} />
and rendered
<ProductConsumer>
{(context) => <Form context={context} />}
</ProductConsumer>
Answer suggested by Metafield on Scrimba Discord Community. Thanks a ton!
You can and should use state to update any variable in a React component! CheckOut is a functional component. To use state in a functional component you have to use a hook, which is useState.
To get value from CartList and CartTotal and update Order, pass callback functions from CheckOut component.
Please check the following code, hope it helps.
import React, { useState } from "react";
import emailjs from "emailjs-com";
import "./form.css";
import { ProductConsumer } from "../../context";
import CartList from "./CartList";
import CartColumns from "./CartColumns";
import CartTotals from "./CartTotals";
import Title from "../Title";
import { ProductProvider } from "../../context";
import CartItem from "./CartItem";
export default function CheckOut() {
// Order default value is empty array. i.e. no orders
// updateOrder will update Order
const [Order, updateOrder] = useState([]);
// cartTotal to store CartTotals value
// updateCartTotal will update cartTotal
const [cartTotal, updateCartTotal] = useState(0);
function sendEmail(e) {
alert("Your order has been placed!");
e.preventDefault();
// You can access Order and cartTotal here.
console.log(Order, cartTotal);
emailjs
.sendForm(
"gmail",
"template_3DAGPnwJ",
e.target,
"user_m49ol85bvoqFluF8IKatG"
)
.then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
}
return (
<div>
<ProductConsumer>
{(value) => {
return (
<div>
<Title name="Check" title="Out" />
<CartColumns />
{/* updateOrder is a callback passed by prop */}
<CartList value={value} onCartUpdate={updateOrder} />
{/* updateCartTotal is a callback passed by prop */}
<CartTotals value={value} onCartTotalUpdate={updateCartTotal} />
</div>
);
}}
</ProductConsumer>
<form className="contact-form" onSubmit={sendEmail}>
<label>Contact Number eg. 12345678 </label>
<input
type="tel"
name="contact_number"
placeholder="12345678"
pattern="[0-9]{8}"
required
/>
<label>Name</label>
<input type="name" name="user_name" required />
<label>Email</label>
<input type="email" name="user_email" required />
<label>Address Line 1</label>
<input type="address-line1" name="user_address1" required />
<label>Address Line 2</label>
<input type="address-line2" name="user_address2" />
<label>Message (eg. Special Requests)</label>
<textarea name="message_html" />
<input type="submit" value="Place Order" />
<textarea name="proudct order" value={Order} />
</form>
</div>
);
}
I see your input fields are uncontrolled! React suggests to use a controlled component for form input. You can get idea from here - https://reactjs.org/docs/forms.html#controlled-components
Also, since you are learning React I suggest you read about two core parts of React. They are props and state.
For working with forms you can check this popular form handling library for react. https://formik.org/

I have a form component I am passing to App.js but I am getting this error

Getting this error when render the app.
SignIn(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
SignIn.js
import React, { useState, useRef } from "react";
import axios from "axios";
import swal from "sweetalert";
import "./SignUp.css";
import image from './img/signup.jpg'
const SignIn = () => {
const [creds, setCreds] = useState({ userName: "", password: "" });
const usernameFieldRef = useRef();
const passwordFieldRef = useRef();
const changeHandler = e => {
setCreds({ ...creds, [e.target.name]: e.target.value });
};
const handleSubmit = event => {
event.preventDefault();
console.log('login');
const username = usernameFieldRef.current.value;
const password = passwordFieldRef.current.value;
axios
.post("https://foodiefun-api.herokuapp.com/api/auth/login", {
username,
password
})
.then(res => {
console.log("DATA", res.data)
localStorage.setItem('token', res.data.token)
swal(
"Welcome to Foodie Fun!",
"You are now signed in, enjoy your stay!",
"success"
);
})
.catch(err => {
console.log('LOGIN FAILED', err.response); // There was an error creating the data and logs to console
});
return (
<div class="page-content">
<div class="form-v6-content">
<div class="form-left">
<img className="form-image" style={{ linearGradient: "red, blue", opacity: ".6" }} src={image} alt="form" />
</div>
<form
onSubmit={handleSubmit}
class="form-detail"
method="post">
<h2>Register Form</h2>
<div class="form-row">
<input
ref={usernameFieldRef}
onChange={changeHandler}
// value={creds.userName}
type="text"
name="id"
id="user-name"
class="input-text"
placeholder="Enter Desired User Name"
required />
</div>
<div class="form-row">
<input
ref={passwordFieldRef}
onChange={changeHandler}
value={creds.password}
type="password"
name="password"
id="password"
class="input-text"
placeholder="Password"
required />
</div>
<div class="form-row">
<input
type="password"
name="comfirm-password"
id="comfirm-password"
class="input-text"
placeholder="Comfirm Password"
required />
</div>
<div class="form-row-last">
<input type="submit"
name="register"
class="register"
value="Register" />
</div>
</form>
</div>
</div>
)
}
}
export default SignIn
App.js
import React, { useState } from "react";
import "./App.css";
import Form from "./Components/SignIn";
import ReviewForm from "./Components/ReviewForm/ReviewForm";
import UserInfo from "./Components/userInfo";
import mockarray from "./Components/mockarray";
import Navbar from "./Components/Navbar";
import RecipeApp from "./recipes/RecipeApp";
import SignUp from "./Components/SignUp";
import SignIn from "./Components/SignIn";
const App = () => {
const [reviews, setReviews] = useState([]);
const addReview = restaurant => {
setReviews([...reviews, { ...restaurant, id: Date.now() }]);
};
return (
<div className="App">
<Navbar />
<SignUp />
<SignIn />
{/* <RecipeApp /> */}
{/* <ReviewForm /> */}
{/* <ReviewForm addReview={addReview} /> */}
{console.log(reviews)}
{/* <UserInfo data = {mockarray} /> */}
</div>
);
};
export default App;
Two forms should be rendering on the screen but when I comment in the SignIn page I get this error. A couple of people have looked at it and they both say everything is right. I'm stumped!
Your return statement is inside the handleSubmit function.
You need to return your state outside handleSubmit function :
import React, { useState, useRef } from "react";
import axios from "axios";
import swal from "sweetalert";
import "./SignUp.css";
import image from './img/signup.jpg'
const SignIn = () => {
const [creds, setCreds] = useState({ userName: "", password: "" });
const usernameFieldRef = useRef();
const passwordFieldRef = useRef();
const changeHandler = e => {
setCreds({ ...creds, [e.target.name]: e.target.value });
};
const handleSubmit = event => {
event.preventDefault();
console.log('login');
const username = usernameFieldRef.current.value;
const password = passwordFieldRef.current.value;
axios
.post("https://foodiefun-api.herokuapp.com/api/auth/login", {
username,
password
})
.then(res => {
console.log("DATA", res.data)
localStorage.setItem('token', res.data.token)
swal(
"Welcome to Foodie Fun!",
"You are now signed in, enjoy your stay!",
"success"
);
})
.catch(err => {
console.log('LOGIN FAILED', err.response); // There was an error creating the data and logs to console
});
}
return (
<div class="page-content">
<div class="form-v6-content">
<div class="form-left">
<img className="form-image" style={{ linearGradient: "red, blue", opacity: ".6" }} src={image} alt="form" />
</div>
<form
onSubmit={handleSubmit}
class="form-detail"
method="post">
<h2>Register Form</h2>
<div class="form-row">
<input
ref={usernameFieldRef}
onChange={changeHandler}
// value={creds.userName}
type="text"
name="id"
id="user-name"
class="input-text"
placeholder="Enter Desired User Name"
required />
</div>
<div class="form-row">
<input
ref={passwordFieldRef}
onChange={changeHandler}
value={creds.password}
type="password"
name="password"
id="password"
class="input-text"
placeholder="Password"
required />
</div>
<div class="form-row">
<input
type="password"
name="comfirm-password"
id="comfirm-password"
class="input-text"
placeholder="Comfirm Password"
required />
</div>
<div class="form-row-last">
<input type="submit"
name="register"
class="register"
value="Register" />
</div>
</form>
</div>
</div>
)
}
export default SignIn
Working code : https://codesandbox.io/s/divine-field-kkfd6
Not sure if it's a typo on the code of your question or in your acctual code but the return is inside handleSubmit.
import React, { useState, useRef } from 'react'
import axios from 'axios'
import swal from 'sweetalert'
import './SignUp.css'
import image from './img/signup.jpg'
const SignIn = () => {
const [creds, setCreds] = useState({ userName: '', password: '' })
const usernameFieldRef = useRef()
const passwordFieldRef = useRef()
const changeHandler = e => {
setCreds({ ...creds, [e.target.name]: e.target.value })
}
const handleSubmit = event => {
event.preventDefault()
console.log('login')
const username = usernameFieldRef.current.value
const password = passwordFieldRef.current.value
axios
.post('https://foodiefun-api.herokuapp.com/api/auth/login', {
username,
password
})
.then(res => {
console.log('DATA', res.data)
localStorage.setItem('token', res.data.token)
swal(
'Welcome to Foodie Fun!',
'You are now signed in, enjoy your stay!',
'success'
)
})
.catch(err => {
console.log('LOGIN FAILED', err.response) // There was an error creating the data and logs to console
})
}
return (
<div className="page-content">
<div className="form-v6-content">
<div className="form-left">
<img
className="form-image"
style={{ linearGradient: 'red, blue', opacity: '.6' }}
src={image}
alt="form"
/>
</div>
<form onSubmit={handleSubmit} className="form-detail" method="post">
<h2>Register Form</h2>
<div className="form-row">
<input
ref={usernameFieldRef}
onChange={changeHandler}
// value={creds.userName}
type="text"
name="id"
id="user-name"
className="input-text"
placeholder="Enter Desired User Name"
required
/>
</div>
<div className="form-row">
<input
ref={passwordFieldRef}
onChange={changeHandler}
value={creds.password}
type="password"
name="password"
id="password"
className="input-text"
placeholder="Password"
required
/>
</div>
<div className="form-row">
<input
type="password"
name="comfirm-password"
id="comfirm-password"
className="input-text"
placeholder="Comfirm Password"
required
/>
</div>
<div className="form-row-last">
<input
type="submit"
name="register"
className="register"
value="Register"
/>
</div>
</form>
</div>
</div>
)
}
export default SignIn

How to handle submitted values in my form using redux-form and serverside validation?

I'm using redux-form with a login form component in ReactJS.
But when I pass values to my form and I click on the submit button the values returned by the console.log are empty, and I don't know how to debug that.
Here's my form component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link, withRouter } from 'react-router-dom';
import {reduxForm, Field} from 'redux-form';
import classnames from 'classnames'
// Actions
import {signin} from '../../actions/auth';
// Bootstrap
import { Grid, Row, Col, Image } from 'react-bootstrap';
// Includes
import '../../assets/css/users/signin.min.css';
import logo from '../../assets/images/datazonia_icone.png';
const renderField = ({input, label, type, forgotPassword=false, meta: {touched, error}}) =>(
<div className="form-group">
<label>{label}</label>
<input {...input} type={type}/>
{forgotPassword &&
<span className="forgot-pw">
<Link to="/users/password/reset">mot de passe oubliƩ ?</Link>
</span>}
{touched &&
error &&
<span className="help-block">
{error}
</span>}
</div>);
let SigninForm = (props) => {
const {handleSubmit, submitting, error } = props;
return (
<form onSubmit={handleSubmit}>
<Field
name="login"
component={renderField}
type='text'
input={{
className: "form-control"
}}
label="Email ou nom d'utilisateur"
/>
<Field
name="password"
component={renderField}
type="password"
input={{
className: "form-control"
}}
label='Mot de passe'
forgotPassword
/>
{error &&
<strong>
{error}
</strong>}
<button disabled={submitting} type="submit" className="btn btn-block btn-datazonia">Connexion</button>
</form>
);
};
SigninForm = reduxForm({
form: 'signin'
})(SigninForm);
class UserSignin extends Component {
onSubmit = (values) => {
console.log(values);
return this.props.signin(values, this.props.history, 'users');
};
render() {
return (
<div className="UserSignin">
<Grid>
<Row className="show-grid bloc-sign">
<Col sm={4} smOffset={4} xs={12} className="text-center title">
<Link to="/">
<Image src={logo} responsive className="center-block"/>
</Link>
<h3>Se connecter</h3>
</Col>
<Col sm={4} smOffset={4} xs={12}>
<div className="signin-form">
<SigninForm onSubmit={this.onSubmit}/>
</div>
</Col>
</Row>
</Grid>
</div>
);
}
}
UserSignin = connect(null, {signin})(withRouter(UserSignin));
export default UserSignin;
My values are empty when i click on the submit button, how can i get it to work ?
(And sorry for my English, I'm French)
OK, I've resolved this issue.
the problem was
input={{
className: "form-control"
}}
overrides the default behavior of redux-form

Resources