The aim: Pass the value of state.TNC and state.promos into the emailjs.sendForm.
Submitted email should see 'true' if the box is checked, false if not.
I am lost for words as to what I need to google to find a resolution that involves semantic and emailjs...
Here is my code that I thought was going to do that for me.
value={this.state.promos}
value={this.state.TNC}
These are the states they should be returning as the values and being passed into the emailjs e.target
this.state = {
TNC: false,
promos: true,
};
The code for the two checkboxes, (I have tried them with and without the value={this.state.TNC})
<Form.Group widths="equal">
<Form.Field>
<Checkbox
label="I agree to the Terms and Conditions"
required
control={Checkbox}
data="TNC"
onChange={this.onToggle}
value={this.state.TNC}
/>
</Form.Field>
<Form.Field>
<Checkbox
label="Send me occasional updates and promotions"
defaultChecked
control={Checkbox}
data="promos"
value={this.state.promos}
onChange={this.onTogglePromos}
/>
</Form.Field>
</Form.Group>
Here is the full code, and you can find a semi-functional version of the form at https://test.ghostrez.net
import emailjs from "emailjs-com";
import { Component } from "react";
import { Button, Checkbox, Form, Input, TextArea } from "semantic-ui-react";
export default class ContactUs extends React.Component {
constructor(props) {
super(props);
this.state = {
TNC: false,
promos: true,
};
}
onToggle = () => {
const TNC = !this.state.TNC;
this.setState({ TNC });
};
onTogglePromos = () => {
const promos = !this.state.promos;
this.setState({ promos });
};
sendEmail = (e, props) => {
e.preventDefault();
if (this.state.TNC !== false) {
return emailjs
.sendForm("tester", "testiTemp", e.target, "user_EPYkKnHwiytfdolol565ljQTCbJkzO7YD")
.then(
(result) => {
alert("Email sent successfully!");
e.target.reset();
},
(error) => {
alert("Email send failed... :( I had one job...");
}
);
} else {
return alert(
"You need to accept the Terms and Conditions before proceeding."
);
}
};
render() {
return (
<Form onSubmit={this.sendEmail}>
<Form.Group widths="equal">
<Form.Field
id="firstName"
control={Input}
label="First name"
name="firstName"
placeholder="First name"
required
/>
<Form.Field
id="lastName"
name="lastName"
control={Input}
label="Last name"
placeholder="Last name"
/>
</Form.Group>
<Form.Group widths="equal">
<Form.Field
id="Email"
control={Input}
label="Email"
name="email"
placeholder="joe#schmoe.com"
required
/>
<Form.Field
id="Phone"
control={Input}
label="Phone"
name="phone"
placeholder="0469 420 689"
required
/>
</Form.Group>
<Form.Field
id="Message"
control={TextArea}
label="Message"
name="message"
placeholder="Message"
required
/>
<Form.Group widths="equal">
<Form.Field>
<Checkbox
label="I agree to the Terms and Conditions"
required
control={Checkbox}
data="TNC"
onChange={this.onToggle}
value={this.state.TNC}
/>
</Form.Field>
<Form.Field>
<Checkbox
label="Send me occasional updates and promotions"
defaultChecked
control={Checkbox}
data="promos"
value={this.state.promos}
onChange={this.onTogglePromos}
/>
</Form.Field>
</Form.Group>
<Form.Field
id="Submit"
control={Button}
type="submit"
value="submit"
positive
content="Submit"
/>
</Form>
);
}
}
Thank you for your help, I really appreciate it.
In order to check, the property is not value but checked, try with this :
<Checkbox
label="I agree to the Terms and Conditions"
required
control={Checkbox}
data="TNC"
onChange={this.onToggle}
checked={this.state.TNC}
/>
This the solution that worked for me, although it only displays if true (checkbox is checked)
I have added id value and value&checked both as (this.state.*state*)
My solution was as follows
<Form.Group widths="equal">
<Form.Field>
<Checkbox
id="Accept_TnCs"
label="I agree to the Terms and Conditions"
required
control={Checkbox}
name="TNC"
value={this.state.TNC}
checked={this.state.TNC}
onChange={this.onToggle}
/>
</Form.Field>
<Form.Field>
<Checkbox
id="Accept_Promos"
label="Send me occasional updates and promotions"
defaultChecked
control={Checkbox}
name="promos"
value={this.state.promos}
checked={this.state.promos}
onChange={this.onTogglePromos}
/>
</Form.Field>
</Form.Group>
Related
I am creating a form using react-bootstrap, react-hook-form, and yup for validation.
I have several fields that are not required like url and radio.
I have used a custom regex instead of yup's url() as it is really strict, for example not accepting google.com or www.google.com.
Also, there are radio type fields like offerInternships, offerVisaSponsorships, offerRemoteWorking which I have declared as notRequired in yup's schema.
The problem is when I press submit button, errors are shown indicating that they must be filled, and I only be able to proceed if I filled them with correct values.
I am not really sure what could have gone wrong here.
Edit 1: I have modified the regex to accept empty strings by adding |^$ at the end of re, and the url now can accept empty strings and act as if it's not required (I am not sure if this actually fixes the problem), but the radio type's problem still exists.
import { Container, Row, Col, Button, Form } from "react-bootstrap";
import * as yup from "yup";
import { useForm } from "react-hook-form";
import { yupResolver } from "#hookform/resolvers/yup";
/**
* Company's validation schema.
*/
const re =
/^((ftp|http|https):\/\/)?(www.)?(?!.*(ftp|http|https|www.))[a-zA-Z0-9_-]+(\.[a-zA-Z]+)+((\/)[\w#]+)*(\/\w+\?[a-zA-Z0-9_]+=\w+(&[a-zA-Z0-9_]+=\w+)*)?$/gm;
const formSchema = yup.object().shape({
url: yup.string().matches(re, "Enter a valid URL!").required(),
name: yup.string().required(),
location: yup.object().shape({
country: yup.string().required(),
state: yup.string().required(),
city: yup.string().required(),
address: yup.string().required(),
}),
offerInternships: yup.bool().default(false).notRequired(),
offerRemoteWork: yup.bool().default(false).notRequired(),
offerVisaSponsorship: yup.bool().default(false).notRequired(),
socialMedia: yup.object().shape({
Linkedin: yup.string().matches(re, "Enter a valid URL!").notRequired(),
GitHub: yup.string().matches(re, "Enter a valid URL!").notRequired(),
}),
});
const RequestForm = () => {
const {
register,
handleSubmit,
watch,
formState: { errors },
} = useForm({
resolver: yupResolver(formSchema),
mode: "all",
});
/**
* Handling the submittion of the form
*/
const onSubmit = async (data) => {
try {
console.log(errors);
console.log(data);
} catch (error) {
console.log(error);
}
};
return (
<>
<Container id="RequestForm-UserForm" className="mt-5 outer-border p-5">
<Form onSubmit={handleSubmit(onSubmit)}>
<Row id="company-details-row">
<Col id="company-details-row-input" sm={12} md={9}>
<Form.Group className="mb-2" controlId="formBasicEmail">
<Form.Label>Company's name</Form.Label>
<Form.Control
type="text"
placeholder="e.g. Microsoft"
{...register("name")}
isInvalid={!!errors?.name}
/>
</Form.Group>
<Form.Group className="mb-2" controlId="formBasicEmail">
<Form.Label>Company's website</Form.Label>
<Form.Control
type="text"
placeholder="e.g. https://www.microsoft.com"
{...register("url")}
isInvalid={!!errors.url}
/>
</Form.Group>
<h3 className="mb-0">Location</h3>
<Form.Group className="mb-2" controlId="formBasicEmail">
<Form.Label>Country</Form.Label>
<Form.Control
type="text"
placeholder="e.g. Egypt, United States of America,...etc."
{...register("location.country")}
isInvalid={!!errors.location?.country}
/>
</Form.Group>
<Form.Group className="mb-2" controlId="formBasicEmail">
<Form.Label>State/Governorate</Form.Label>
<Form.Control
type="text"
placeholder="e.g. Cairo, California, Berlin...etc."
{...register("location.state")}
isInvalid={!!errors.location?.state}
/>
</Form.Group>
<Form.Group className="mb-2" controlId="formBasicEmail">
<Form.Label>City</Form.Label>
<Form.Control
type="text"
placeholder="e.g. Maadi, San Francisco,...etc."
{...register("location.city")}
isInvalid={!!errors.location?.city}
/>
</Form.Group>
<Form.Group className="mb-2" controlId="formBasicEmail">
<Form.Label>Address</Form.Label>
<Form.Control
type="text"
placeholder="e.g. 14th Zaki Sayed St."
{...register("location.address")}
isInvalid={!!errors.location?.address}
/>
</Form.Group>
<h3 className="mt-2 mb-0">Social Media</h3>
<Form.Group className="mb-2" controlId="formBasicEmail">
<Form.Label>
<i className="icon ion-social-linkedin"></i> Linkedin
</Form.Label>
<Form.Control
type="text"
placeholder="e.g. https://www.linkedin.com/company/x"
{...register("socialMedia.Linkedin")}
isInvalid={!!errors.socialMedia?.Linkedin}
/>
</Form.Group>
<Form.Group className="mb-2" controlId="formBasicEmail">
<Form.Label>
<i className="icon ion-social-github"></i> GitHub
</Form.Label>
<Form.Control
type="text"
placeholder="e.g. https://www.github.com/company"
{...register("socialMedia.GitHub")}
isInvalid={!!errors.socialMedia?.GitHub}
/>
</Form.Group>
<h3 className="mt-2 mb-0">Culture & Environment</h3>
<div id="offer-Internship" key={"inline-radio-internships"}>
<Form.Label>Does your company offer internships? π</Form.Label>
<br></br>
<Form.Check
inline
label="Yes"
value={"true"}
{...register("offerInternships", { required: false })}
type={"radio"}
isInvalid={!!errors.offerInternships}
/>
<Form.Check
inline
label="No"
value={"false"}
{...register("offerInternships", { required: false })}
type={"radio"}
isInvalid={!!errors.offerInternships}
/>
</div>
<div id="offer-VisaSponsorship" key={"inline-radio-visa"}>
<Form.Label>
Does your company offer visa sponsorship? βοΈ
</Form.Label>
<br></br>
<Form.Check
inline
label="Yes"
value={"true"}
{...register("offerVisaSponsorship", { required: false })}
type={"radio"}
isInvalid={!!errors.offerVisaSponsorship}
/>
<Form.Check
{...register("offerVisaSponsorship", { required: false })}
inline
label="No"
value={"false"}
type={"radio"}
isInvalid={!!errors.offerVisaSponsorship}
/>
</div>
<div id="offer-remoteWork" key={"inline-radio-remote"}>
<Form.Label>
Does your company offer remote working? πΊοΈ
</Form.Label>
<br></br>
<Form.Check
{...register("offerRemoteWork", { required: false })}
inline
label="Yes"
value={"true"}
type={"radio"}
isInvalid={!!errors.offerRemoteWork}
/>
<Form.Check
{...register("offerRemoteWork", { required: false })}
inline
label="No"
value={"false"}
type={"radio"}
isInvalid={!!errors.offerRemoteWork}
/>
</div>
</Col>
</Row>
<Row id="company-submit text-center">
<Col className={"text-center"} sm={12}>
<h2 className="fs-1 main-color-1-dark">
We have reached to the end of the form! π
</h2>
<Button variant="success" type="submit" className="rubik-font">
Submit form
</Button>
</Col>
</Row>
</Form>
</Container>
</>
);
};
export default RequestForm;
In the below form component how can we hide the certain input components ?
#1 how can we pass display: none to certain component?
#2 tried to set the state and mount but throwing errors while rendering.
const inputStyle = {
display:none
}
and pass the style = {inputStyle} to effect certain components
is there any effective way to condtionally render the below form and hide the different components for different domains?
import React from 'react'
class ClassComponentForm extends React.Component {
state = {}
componentDidMount(){
this.setState(emptyForm)
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
render(){
return(
<div id='classComponentForm'>
<h2>
Please Enter Your Information - Class
</h2>
<form id='form'>
<label htmlFor='nameInput'>
Name:
</label>
<input
id='nameInput'
name='name'
type='text'
placeholder='Please type your name'
value={this.state.name}
onChange={(e) => this.handleChange(e)}
/>
<label htmlFor='emailInput'>
Email:
</label>
<input
id='emailInput'
name='email'
type='text'
placeholder='Please type your email'
value={this.state.email}
onChange={(e) => this.handleChange(e)}
/>
<label htmlFor='zipcodeInput'>
Zipcode:
</label>
<input
id='zipcodeInput'
name='zipcode'
type='text'
placeholder='Please type your zipcode'
value={this.state.zipcode}
onChange={(e) => this.handleChange(e)}
/>
<label htmlFor='dateInput'>
Date:
</label>
<input
id='dateInput'
name='date'
type='date'
value={this.state.date}
onChange={(e) => this.handleChange(e)}
/>
</form>
</div>
)
}
}
export default ClassComponentForm
handleChange setup keys inside state object based on input name (because of e.target.name) which you defined in the input element. You already access this value inside the value prop
value={this.state.email}
The same thing can be used to conditionally hide each input. This is an example of how you can hide email input.
{this.state.email && <input
id='emailInput'
name='email'
type='text'
placeholder='Please type your email'
value={this.state.email}
onChange={(e) => this.handleChange(e)}
/>}
I'm new to React and just started working with state so please bare with me. I also found a lot of similar questions but nothing that really addresses the following:
I have a reactstrap form that has disabled FormControls. When the user clicks the 'edit' button the FormControls need to be enabled. According to my knowledge, this should be simple with JSX but nothing I've tried has worked. It might just be a stupid implementation error on my side.
class UserProfile extends React.Component {
constructor(props) {
super(props);
this.state = {
editToggle: false,
userName: "Star Lord",
accTier: "Premium",
credit: "95 855 651",
vehicle: "The Milano",
contact: "Echoe Golf Oscar 12.465Ghz"
}
// This binding is necessary to make `this` work in the callback
this.editInputToggle = this.editInputToggle.bind(this);
}
editInputToggle() {
this.setState(prevState => ({
editToggle: !prevState.editToggle
}));
}
onValueChange = (e) => {
this.setState({ fullName: e.target.value });
};
render() {
const { editToggle } = this.state;
// We need give the components function a return statement.
return (
/* The Component can only return one parent element,
while parent elements can have many children */
<div className='profileDetails'>
{/* Bootstrap Form is used for the form
Bootstrap Button is used for the edit button */}
<Form id='formProfile'>
<Form.Group className="mb-3" controlId="formProfileDetails">
<Form.Label>US3RNAME:</Form.Label>
<Form.Control type="text" value={this.state.userName}
onChange={this.onValueChange} className='user-info' />
<Form.Label>ACC0uNT TI3R:</Form.Label>
<Form.Control disabled type="text" value={this.state.accTier} onChange={this.onValueChange} className='user-info' />
<Form.Label>CR3DiT:</Form.Label>
<Form.Control disabled type="text" value={this.state.credit} onChange={this.onValueChange} className='user-info' />
<Form.Label>R3GiSTERED VEHiCL3:</Form.Label>
<Form.Control disabled type="text" value={this.state.vehicle} onChange={this.onValueChange} className='user-info' />
<Form.Label>C0NTACT D3TAiLS:</Form.Label>
<Form.Control disabled type="text" value={this.state.contact} onChange={this.onValueChange} className='user-info' />
</Form.Group>
<Button variant="light" size="sm" className='p-2 m-4 headerBtn' onClick={ () => this.editInputToggle(editToggle) }>
Edit
</Button>
</Form>
</div>
);
}
}
What do I need to do to change "disabled" to ""?
For enabling the FormControl,
<Form.Control disabled={!this.state.editToggle} type="text" value={this.state.accTier} onChange={this.onValueChange} className='user-info' />
Try replacing "disabled" with this line: disabled={this.state.editToggle ? "true" : "false"}
I apologise if my post is poorly formatted, I'm not experienced in either JS/React or Stack overflow
This is my 7th iteration in two days of attempting to get my contact form to work completely. I've had it working to the point that the only items not being sent through on the submission email is the TNC and promos box.
I need the Checkboxes to send true or false depending on whether they are checked or not. bonus points if I can convert the true or false to yes and no
The Error I am getting is
Failed to compile.
./src/Components/ContactForm.jsx
Line 37: 'sendEmail' is not defined no-undef
Here is the affected line
<Form onSubmit={sendEmail}>
Here is my "sendMail" arrow function
sendEmail = (e) => {
e.preventDefault();
emailjs.sendForm("test", "testTemp", e.target, "user_EPYkKnHwljQTCbJkzO7YD9")
.then(
(result) => {
alert(+"Email sent successfully!");
e.target.reset();
},
(error) => {
alert("Email send failed... :( I had one job...");
}
);
};
I have an old non-functional version of the contact form on https://test.ghostrez.net if it may help in any way.
Here is the full 'ContactForm.jsx' in case it helps.
import React from "react";
import emailjs from "emailjs-com";
import { Component } from "react";
import { Button, Checkbox, Form, Input, TextArea } from "semantic-ui-react";
export default class ContactUs extends React.Component {
constructor(props) {
super(props);
this.state = {
TNC: false,
promos: true,
};
}
onToggle = () => {
const TNC = !this.state.TNC;
this.setState({ TNC });
};
onTogglePromos = () => {
const promos = !this.state.promos;
this.setState({ promos });
};
sendEmail = (e) => {
e.preventDefault();
emailjs.sendForm("test", "testTemp", e.target, "user_EPYkKnHwljQTCbJkzO7YD9")
.then(
(result) => {
alert(+"Email sent successfully!");
e.target.reset();
},
(error) => {
alert("Email send failed... :( I had one job...");
}
);
};
render() {
return (
<Form onSubmit={sendEmail}>
<Form.Group widths="equal">
<Form.Field
id="firstName"
control={Input}
label="First name"
name="firstName"
placeholder="First name"
required
/>
<Form.Field
id="lastName"
name="lastName"
control={Input}
label="Last name"
placeholder="Last name"
/>
</Form.Group>
<Form.Group widths="equal">
<Form.Field
id="Email"
control={Input}
label="Email"
name="email"
placeholder="joe#schmoe.com"
onChange=""
required
/>
<Form.Field
id="Phone"
control={Input}
label="Phone"
name="phone"
placeholder="0469 420 689"
required
/>
</Form.Group>
<Form.Field
id="Message"
control={TextArea}
label="Message"
name="message"
placeholder="Message"
required
/>
<Form.Group widths="equal">
<Form.Field>
<Checkbox
label="I agree to the Terms and Conditions"
required
control={Checkbox}
data="TNC"
onChange=''
/>
</Form.Field>
<Form.Field>
<Checkbox
label="Send me occasional updates and promotions"
defaultChecked
control={Checkbox}
data="promos"
onChange=''
/>
</Form.Field>
</Form.Group>
<Form.Field
id="Submit"
control={Button}
type="submit"
value="submit"
positive
content="Submit"
/>
</Form>
);
}
}
You are referring to sendEmail in the following statement:
<Form onSubmit={sendEmail}>
However, sendEmail is a member of the ContactUs component/instance. You will have to reference it by using this.sendEmail.
<Form onSubmit={this.sendEmail}>
My react app is not redirecting to the dashboard page after submitting a form. I tried using react-router-dom Redirect function but still with no success. I then opt-in for Browser History. push but still no success.
for the latter trial, the URL changes to /dashboard but the component remains on the form page, it doesn't move to dashboard until I reload the page
form field
<form>
<Input
displayValidationErrors={displayValidationErrors("fullname", validators)}
name="fullname"
type="text"
label="Full Name"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("password", validators)}
name="password"
type="password"
label="Password"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("password2", validators)}
name="password2"
type="password"
label="Confirm Password"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("email", validators)}
name="email"
type="email"
label="Email Address"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors(
"phone_number",
validators
)}
name="phone_number"
type="number"
label="Phone Number"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("card_number", validators)}
value={data.card_number}
name="card_number"
type="text"
label="Card Number"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("date", validators)}
value={data.date}
name="date"
type="text"
label="Expiry Date"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<Input
displayValidationErrors={displayValidationErrors("pin", validators)}
name="pin"
type="password"
label="PIN"
onChange={(e) => handleInputChange(e.target.name, e.target.value)}
/>
<div className="col-lg-12 loginbttm">
<div className=" login-btm login-button">
<Button
handleClick={onSubmit}
type="submit"
className="btn btn-primary"
label="SUBMIT"
disabled={!isFormValid(validators)}
/>
</div>
</div>
</form>;
onSubmit function
const onSubmit = (e) => {
e.preventDefault();
browserHistory.push("/dashboard");
};
Button Component
const Button = ({ type, className, handleClick, label, disabled }) => (
<button
type={type}
className={className}
onClick={handleClick}
disabled={disabled}
>
{label}
</button>
);
My app.js
function App() {
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/dashboard">
<Dashboard />
</Route>
<Route exact path="/">
<Form />
</Route>
</Switch>
</div>
</Router>
);
}
export default App;
I don't see createBrowserHistory or something like <Router history={history}> so I guess you are using the default browser history. In that case you need withRouter to make it work:
import React from "react";
import { withRouter } from "react-router-dom";
function App() {
const onSubmit = (e) => {
e.preventDefault()
this.props.history.push("/personalInfo");
}
...
}
export default withRouter(App);
More about withRouter solution here
More about createBrowserHistory solution here
For functional component with react-router V5, you can also do with hooks:
import { useHistory } from "react-router-dom";
function App() {
let history = useHistory();
const onSubmit = (e) => {
e.preventDefault()
history.push('/dashboard');
}
return (
<Router>
<div className="App">
...
</div>
</Router>
);
}
Take a look at this to know more about useHistory
try using below. hope it'll help
this.props.history.push({
pathname: '/dashboard'
})
Another way of doing it with the function component -
import {withRouter} from "react-router-dom";
function SignIn({history}) {
const submit = (event) => {
event.preventDefault();
history.push("/profile");
}
....
}
export default withRouter(SignIn)