Npm reactjs -input -validators - reactjs

index.js:1446 Warning: React does not recognize the validatorErrMsg prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase validatorerrmsg instead. If you accidentally passed it from a parent component, remove it from the DOM element.
in input (created by t)
in div (created by t)
in t (created by t)
in div (created by t)
in t (created by t)
in div (created by t).
This is the Error which stuck my brain since two days..
The required js file include following code .
class SharedComponent extends Component {
constructor() {
super();
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
data: {},
};
}
handleChange(event, inputValue, inputName, validationState, isRequired) {
const value = (event && event.target.value) || inputValue;
const { data } = this.state;
data[inputName] = { value, validation: validationState, isRequired };
this.setState({
data,
});
const formData = formInputData(this.state.data);
const isFormValid = formValidation(this.state.data);
console.log('shared component',formData+isFormValid);
}
handleSubmit(event) {
event.preventDefault();
const isFormValid = formValidation(this.state.data);
if (isFormValid) {
// do anything including ajax calls
this.setState({ callAPI: true });
} else {
this.setState({ callAPI: true, shouldValidateInputs: !isFormValid });
}
}
render() {
const passwordValue = this.state.data.password && this.state.data.password.value;
return (
<form className="example">
<Row>
<Col md={6}>
<Field required
label="Full Name" name="fullName" placeholder="First Last"
onChange={this.handleChange}
value={this.state.data.fullName}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
<Col md={6}>
<Field
validator="isEmail" required
label="Email" name="email" placeholder="Email"
onChange={this.handleChange}
value={this.state.data.email}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
</Row>
<Row>
<Col md={6}>
<Field
validator="isAlphanumeric" required minLength={8}
minLengthErrMsg="Short passwords are easy to guess. Try one with atleast 8 characters"
label="Create a password" name="password" type="password" placeholder="Password"
onChange={this.handleChange}
value={this.state.data.password}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
<Col md={6}>
<Field
validator="equals" required comparison={passwordValue}
validatorErrMsg="These passwords don't match. Try again?"
label="Confirm password" name="confirmPassword" type="password" placeholder="Password"
onChange={this.handleChange}
value={this.state.data.confirmPassword}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
</Row>
<Field
required
requiredErrMsg="Enter your address so we can send you awesome stuff"
label="Address" name="address" placeholder="1234 Main St"
onChange={this.handleChange}
value={this.state.data.address}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
<Field
label="Address 2"
name="address2" placeholder="Apartment, studio, or floor"
onChange={this.handleChange}
value={this.state.data.address2}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
<Row>
<Col md={6}>
<Field
maxLength={20} required label="City"
name="inputCity"
onChange={this.handleChange}
value={this.state.data.inputCity}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
<Col md={3}>
<label htmlFor="inputState">State</label>
<select
name="inputState" className="form-control"
onChange={this.handleChange}
value={this.state.data.inputState ? this.state.data.inputState.value : ''}
>
<option>Choose...</option>
<option value="ALABAMA">ALABAMA</option>
<option value="ALASKA">ALASKA</option>
<option value="ARIZONA">ARIZONA</option>
<option>...</option>
</select>
</Col>
<Col md={3}>
<Field
validator="isPostalCode" locale="US" required maxLength={10}
validatorErrMsg="Enter a valid US Zip"
label="Zip" name="inputZip"
onChange={this.handleChange}
value={this.state.data.inputZip}
shouldValidateInputs={this.state.shouldValidateInputs}
/>
</Col>
</Row>
<button
type="submit" onClick={this.handleSubmit} className="btn btn-danger"
>Sign up
</button>
{this.state.callAPI
?
<pre className="resultBlock">
{JSON.stringify(formInputData(this.state.data), null, 4)}
</pre>
: null
}
</form>
);
}
}
This is my js file for rect js form with validation .
Can Anyone help to walk through it ..THANKS.

The message you're seeing means that the Field component isn't itself doing anything with the validatorErrMsg prop; instead, it's simply passing it down to the DOM node (probably an input element). That property has no special meaning to input elements, so it has no effect.
You need to check the documentation for whatever library you're getting Field from. That should specify what props you can use.
Alternatively, if you created the Field component yourself, you need to implement the logic for handling the validatorErrMsg prop yourself, within that component.

Related

Issue with Gatsby Netlify Form not receiving Submissions

I got the Netlify form working and accepting submissions but once I started setting up AJAX according to https://docs.netlify.com/forms/setup/, I can't figure out why submissions aren't being received.
Things I've tried:
Removing Hidden "form-name" input
Removing Recaptcha
Running "gatsby clean"
Removing opening Form tag's method attribute (method: "POST")
Removing action attribute from the opening Form tag and setting it directly in handleSubmit:
.then(() => navigate("/thank-you/"))
Any suggestions or fixes are really appreciated!
contact-form.js:
import React, { setState } from "react"
import styled from "styled-components"
import Recaptcha from "react-google-recaptcha"
import { navigate } from "gatsby"
import { Button, Col, Form, Row } from "react-bootstrap"
import { breakpoints } from "../utils/breakpoints"
const RECAPTCHA_KEY = process.env.GATSBY_RECAPTCHA_KEY
export default function ContactForm() {
const [state, setState] = React.useState({})
const recaptchaRef = React.createRef() // new Ref for reCaptcha
const [buttonDisabled, setButtonDisabled] = React.useState(true)
const handleChange = e => {
setState({ ...state, [e.target.name]: e.target.value })
}
const encode = data => {
return Object.keys(data)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
.join("&")
}
const handleSubmit = e => {
e.preventDefault()
const form = e.target
const recaptchaValue = recaptchaRef.current.getValue()
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({
"form-name": "contact",
"g-recaptcha-response": recaptchaValue,
...state,
}),
})
.then(() => navigate(form.getAttribute("action")))
.catch(error => alert(error))
}
return (
<Form
name="contact"
method="POST"
netlify
action="/thank-you"
netlify-honeypot="bot-field"
data-netlify-recaptcha="true"
onSubmit={handleSubmit}
>
<Row>
<Col md={12}>
<h3>Message Us</h3>
</Col>
</Row>
<Row>
<Col md={6}>
<Form.Group hidden>
<Form.Label htmlFor="bot-field">
Bot Field: Humans do not fill out!
</Form.Label>
<Form.Control name="bot-field" />
<Form.Control name="form-name" value="contact" />
</Form.Group>
<Form.Group>
<Form.Label htmlFor="first-name">First Name</Form.Label>
<Form.Control
required
size="lg"
type="text"
name="first-name"
onChange={handleChange}
/>
</Form.Group>
</Col>
<Col md={6}>
<Form.Group>
<Form.Label htmlFor="last-name">Last Name</Form.Label>
<Form.Control
required
size="lg"
type="text"
name="last-name"
onChange={handleChange}
/>
</Form.Group>
</Col>
</Row>
<Row>
<Col md={6}>
<Form.Group>
<Form.Label htmlFor="email">Email</Form.Label>
<Form.Control
required
size="lg"
type="email"
name="email"
onChange={handleChange}
/>
</Form.Group>
</Col>
<Col md={6}>
<Form.Group>
<Form.Label htmlFor="phone">Phone (Optional)</Form.Label>
<Form.Control
size="lg"
type="tel"
name="phone"
onChange={handleChange}
/>
</Form.Group>
</Col>
</Row>
<Row>
<Col md={12}>
<Form.Group>
<Form.Label htmlFor="message">Message</Form.Label>
<Form.Control
required
as="textarea"
rows="3"
placeholder="Enter your message here."
name="message"
onChange={handleChange}
/>
</Form.Group>
</Col>
</Row>
<Row>
<Col md={12}>
<FormControls>
<Recaptcha
ref={recaptchaRef}
sitekey={RECAPTCHA_KEY}
size="normal"
id="recaptcha-google"
onChange={() => setButtonDisabled(false)} // disable the disabled button!
className="mb-3"
/>
<div>
<Button className="mr-3" type="reset" value="Eraser">
Clear
</Button>
<Button type="submit" disabled={buttonDisabled}>
Send
</Button>
</div>
</FormControls>
</Col>
</Row>
</Form>
)
}
const FormControls = styled.div`
display: flex;
align-items: center;
flex-direction: column;
#media ${breakpoints.sm} {
flex-direction: row;
justify-content: space-between;
}
button[disabled] {
cursor: not-allowed;
}
gatsby-config:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
siteMetadata: {
title: `...`,
description: `...`,
author: `...`,
},
flags: {
DEV_SSR: false,
},
plugins: [
`gatsby-plugin-gatsby-cloud`,
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
`gatsby-plugin-styled-components`,
`gatsby-plugin-typography`,
`gatsby-plugin-react-helmet`,
`gatsby-transformer-sharp`,
},
}
HTML File in Static Folder:
<form
data-netlify="true"
name="contactVivaz"
method="POST"
data-netlify-honeypot="bot-field"
data-netlify-recaptcha="true"
>
<input type="text" name="first-name" />
<input type="text" name="last-name" />
<input type="email" name="email" />
<input type="tel" name="phone" />
<textarea name="message"></textarea>
<div data-netlify-recaptcha="true"></div>
</form>
Your state management looks good, what it's mandatory is to have (and to check) the input value of hidden fields that must match exactly the form name in the JSX as well as in the Netlify's dashboard. Assuming that everything is well named, as it seems, I believe your issue comes from the Form component, which should looks like:
<Form
name="contact"
method="POST"
action="/thank-you"
data-netlify-honeypot="bot-field"
data-netlify-recaptcha="true"
data-netlify="true"
onSubmit={handleSubmit}
>
Note the data-netlify-honeypot and data-netlify value.
For adding the reCAPTCHA field, you have two options:
Allowing Netlify to handle all the related logic by adding simply an empty <div> like:
<div data-netlify-recaptcha="true"/>
Adding a custom reCAPTCHA (your case) what required to add the environment variables in your Netlify dashboard (prefixed with GATSBY_) and sending the response with the g-recaptcha-response field so your POST request needs to have that field as the docs suggest:
The Netlify servers will check the submissions from that form, and
accept them only if they include a valid g-recaptcha-response value.
Further references to base your setup:
https://www.gatsbyjs.com/docs/building-a-contact-form/
https://www.seancdavis.com/blog/how-to-use-netlify-forms-with-gatsby/
https://medium.com/#szpytfire/setting-up-netlify-forms-with-gatsby-and-react-5ee4f56a79dc

Radio Buttons in React using Bootstrap always post same value

I am not getting an error, but the radio buttons I am writing are always sending the same value to the database, and I am not sure why or how to fix it.
UPDATE. I have attached the complete code. Hopefully this provides more detail. Everything is working but the radio buttons. Can someone shed some light as to how I can fix this?
import React from "react";
import axios from "axios";
import Form from 'react-bootstrap/Form'
import Row from 'react-bootstrap/Col'
import Button from 'react-bootstrap/Button'
import './Form.css'
class Home extends React.Component {
constructor(props) {
super(props);
this.state = { tickets: [] };
this.firstName = React.createRef();
this.lastName = React.createRef();
this.email = React.createRef();
this.category = React.createRef();
this.content = React.createRef();
this.urgency = React.createRef();
}
componentDidMount() {
this.getData();
}
getData = () => {
// Java Spring Boot uses port 8080
let url = "http://localhost:8080/tickets";
// axios.get(url).then(response => console.log(response.data));
axios.get(url).then(response => this.setState({ tickets: response.data }));
};
addTicket = () => {
let url = "http://localhost:8080/tickets";
axios.post(url, {
firstName: this.firstName.current.value,
lastName: this.lastName.current.value,
email: this.email.current.value,
category: this.category.current.value,
content: this.content.current.value,
urgency: this.urgency.current.value
}).then(response => {
// refresh the data
this.getData();
// empty the input
this.firstName.current.value = "";
this.lastName.current.value = "";
this.email.current.value = "";
this.content.current.value = "";
});
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<Form.Group className="Input">
<Form.Control type="text" name="firstName" placeholder="First Name" ref={this.firstName} />
</Form.Group>
<Form.Group className="Input">
<Form.Control type="text" name="lastName" placeholder="Last Name" ref={this.lastName} />
</Form.Group>
<Form.Group className="Input">
<Form.Control type="text" name="email" placeholder="Email" ref={this.email} />
</Form.Group>
<br></br>
<Form.Group className="dropdown">
<Form.Label>Select a Category:</Form.Label>
<Form.Control as="select" ref={this.category}>
<option value="hardware">Hardware</option>
<option value="software">Software</option>
<option value="internet">Internet</option>
<option value="other">Other</option>
</Form.Control>
</Form.Group>
<br></br>
<Form.Group className="Issue">
<Form.Label>Please Describe Your Issue:</Form.Label>
<Form.Control as="textarea" rows="7" ref={this.content} />
</Form.Group>
<fieldset>
<Form.Group as={Row}>
<Form.Label className="radio" column sm={12}>
Select the Urgency Level:<br></br>
</Form.Label>
<Form.Check className="radioButtons"
type="radio"
label="Urgent"
name="selectedOption"
value="Urgent"
ref={this.urgency}
/>
<Form.Check className="radioButtons"
type="radio"
label="Standard"
name="selectedOption"
value="Standard"
ref={this.urgency}
/>
<Form.Check className="radioButtons"
type="radio"
label="Low Priority"
name="selectedOption"
value="Low Priority"
ref={this.urgency}
/>
</Form.Group>
</fieldset>
<Button variant="secondary" type="button" className="submit" onClick={this.addTicket}>Submit Ticket</Button>
</form>
</div>
);
}
}
export default Home;
The issue is that you are pointing this.urgency to all of your Radio components 1 by 1. Here is a brief simulation of running your code from top to bottom:
<Form.Group as={Row}>
<Form.Label className="radio" column sm={12}>
Select the Urgency Level:<br></br>
</Form.Label>
<Form.Check
value="Urgent"
ref={this.urgency} // <-- this.urgency is now pointing to this 1st component
/>
<Form.Check
value="Standard"
ref={this.urgency} // <-- this.urgency is now pointing to this 2nd component
/>
<Form.Check
value="Low Priority"
ref={this.urgency} // <-- this.urgency is now pointing to this 3rd component
/>
</Form.Group>
So the final reference of this.urgency when the code is finished running is the 3rd component. So when you access this.urgency.current.value it will always return the 3rd component's value (i.e., Low Priority)
In React, you normally use state to hold these values - use ref sparsely and only if you really have to.
Here is an example of a solution:
constructor(props) {
super(props);
this.state = {
tickets: [],
urgency: "" // state for urgency
};
<Form.Group as={Row}>
<Form.Label className="radio" column sm={12}>
Select the Urgency Level:<br></br>
</Form.Label>
<Form.Check
value="Urgent"
onChange={() => this.setState({ urgency: "Urgent" })}
/>
<Form.Check
value="Standard"
onChange={() => this.setState({ urgency: "Standard" })}
/>
<Form.Check
value="Low Priority"
onChange={() => this.setState({ urgency: "Low Priority" })}
/>
</Form.Group>
axios
.post(url, {
urgency: this.state.urgency
})
you ref three elements to the same ref. you can walk around this without changing your login and adding state by helper function. in that way you don't change behavoir of your code (is not perferct ...) but you avoid rendering forced by setState.
import React from "react"
import Form from 'react-bootstrap/Form'
import Row from 'react-bootstrap/Col'
import Button from 'react-bootstrap/Button'
class Home extends React.Component {
constructor(props) {
super(props);
this.state = { tickets: [] };
this.firstName = React.createRef();
this.lastName = React.createRef();
this.email = React.createRef();
this.category = React.createRef();
this.content = React.createRef();
this.urgency = React.createRef();
}
componentDidMount() {
}
getData = () => {
};
addTicket = () => {
console.log({
firstName: this.firstName.current.value,
lastName: this.lastName.current.value,
email: this.email.current.value,
category: this.category.current.value,
content: this.content.current.value,
urgency: this.urgency.current.value
})
};
handleCheckBoxChange(ref, event){
if(event.target.checked){
ref.current = {value: event.target.value}
}
}
render() {
return (
<div>
<form onSubmit={this.addTicket}>
<Form.Group className="Input">
<Form.Control type="text" name="firstName" placeholder="First Name" ref={this.firstName} />
</Form.Group>
<Form.Group className="Input">
<Form.Control type="text" name="lastName" placeholder="Last Name" ref={this.lastName} />
</Form.Group>
<Form.Group className="Input">
<Form.Control type="text" name="email" placeholder="Email" ref={this.email} />
</Form.Group>
<br></br>
<Form.Group className="dropdown">
<Form.Label>Select a Category:</Form.Label>
<Form.Control as="select" ref={this.category}>
<option value="hardware">Hardware</option>
<option value="software">Software</option>
<option value="internet">Internet</option>
<option value="other">Other</option>
</Form.Control>
</Form.Group>
<br></br>
<Form.Group className="Issue">
<Form.Label>Please Describe Your Issue:</Form.Label>
<Form.Control as="textarea" rows="7" ref={this.content} />
</Form.Group>
<fieldset>
<Form.Group as={Row}>
<Form.Label className="radio" column sm={12}>
Select the Urgency Level:<br></br>
</Form.Label>
<Form.Check className="radioButtons"
type="radio"
label="Urgent"
name="selectedOption"
value="Urgent"
onClick={this.handleCheckBoxChange.bind(this, this.urgency)}
/>
<Form.Check className="radioButtons"
type="radio"
label="Standard"
name="selectedOption"
value="Standard"
onClick={this.handleCheckBoxChange.bind(this, this.urgency)}
/>
<Form.Check className="radioButtons"
type="radio"
label="Low Priority"
name="selectedOption"
value="Low Priority"
onClick={this.handleCheckBoxChange.bind(this, this.urgency)}
/>
</Form.Group>
</fieldset>
<Button variant="secondary" type="button" className="submit" onClick={this.addTicket}>Submit Ticket</Button>
</form>
</div>
);
}
}
export default Home;

Two Antd forms, one component

I have two antd forms within a single component. The first form is a register form where a user inputs various information (firstname, lastname, email, etc..) The submit button triggers a function to open a modal with another form for them to verify their phone number by generating a code that is texted to them. Once the code is typed and they hit verify, it verifies if it is the correct code - then i would like for it to register the user but I am having difficulties pulling in the values from the first form..
Is there a specific way to go about doing this? I thought maybe I could utilize useState and set the values to component level state but even that didnt work..
form
<Form
layout="vertical"
name="register-form"
initialValues={initialValues}
onFinish={handleVerification}
>
<Row gutter={ROW_GUTTER}>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="firstName"
label="First Name"
rules={rules.firstName}
hasFeedback
>
<Input placeholder="Enter First Name" />
</Form.Item>
</Col>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="lastName"
label="Last Name"
rules={rules.lastName}
hasFeedback
>
<Input placeholder="Enter Last Name" />
</Form.Item>
</Col>
</Row>
<Row gutter={ROW_GUTTER}>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="phone"
label="Phone Number"
rules={rules.phone}
hasFeedback
>
<Input placeholder="Enter Phone Number" />
</Form.Item>
</Col>
<Col xs={24} sm={24} md={12}>
<Form.Item name="city" label="City" rules={rules.city} hasFeedback>
<Select placeholder="Select City">
<Option value="Lancaster, PA">Lancaster, PA</Option>
</Select>
</Form.Item>
</Col>
</Row>
<Form.Item
name="email"
label="Email Address"
rules={rules.email}
hasFeedback
>
<Input placeholder="Enter Email Address" />
</Form.Item>
<Form.Item
name="password"
label="Password"
rules={rules.password}
hasFeedback
>
<Input.Password placeholder="Enter Password" />
</Form.Item>
<Form.Item
name="confirmPassword"
label="Confirm Password"
rules={rules.confirm}
hasFeedback
>
<Input.Password placeholder="Confirm Password" />
</Form.Item>
<Form.Item name="tos" valuePropName="checked">
<Checkbox>
I agree to the <Link to="/">Terms of Service</Link> and{' '}
<Link to="/">Privacy Policy</Link>.
</Checkbox>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" block>
Register
</Button>
</Form.Item>
</Form>
<Modal
title="Account Verification"
centered
visible={modal}
onOk={() => setModal(false)}
onCancel={() => setModal(false)}
>
<p>
To finish registering, please enter the verification code we just sent
to your phone. If you didn't receive a code, make sure your entered
phone number is correct and sign up again. Your code will expire upon
closing this popup.
</p>
<Form layout="vertical" name="verify-phone-form" onFinish={onSubmit}>
<Form.Item name="enteredCode" label="Verify">
<Input placeholder="Enter Code" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" block>
Verify
</Button>
</Form.Item>
</Form>
</Modal>
handleVerification
const handleVerification = async (values) => {
const { phone, email } = values;
setModal(true);
try {
const response = await postRegisterCheckDuplicate({ email, phone });
if (response.data.success) {
switch (response.data.message) {
case 0:
try {
const response = await dispatch(
attemptRegisterVerify({ to: phone })
);
console.log('handleVerification: ', response.message);
if (response.success) {
setGeneratedCode(response.message);
} else {
console.log(response.message);
}
} catch (error) {
console.log(error);
}
break;
case 1:
console.log('Email Address already in use.');
break;
case 2:
console.log('Phone number already in use.');
break;
case 3:
console.log('Email and Phone in use.');
break;
}
} else {
console.log(response.data.message);
}
} catch (error) {
console.log(error);
}
};
onSubmit
const onSubmit = (values) => {
const { enteredCode } = values;
if (generatedCode === enteredCode) {
try {
console.log('values :', values);
// dispatch(attemptRegister(values));
} catch (error) {
console.log(error);
}
} else {
console.log('Verification code incorrect');
}
};
You can create a form instance (hooks) and reference it to the first form so you can use the api of the instance. You can check more here antd FormInstance
const [registerForm] = Form.useForm();
const handleSubmit = (values) => {
const { enteredCode } = values;
console.log(registerForm.getFieldsValue());
//output is the values in the first form
};
<Form form={registerForm} layout="vertical" onFinish={handleVerification}>
...
</Form>
I created a small version of your work. See working code here:
You can also check this one antd control between forms

how to update dynamically generated form in react js

I have a code here where I have to do update operation. I'm generating the form fields dynamically based on the result of get operation. The form fields are pre-populated. On change event on the input field in triggering an error data.map is not a function on keypress. I can change for single fields with different names. But unable to update json array state. Please help. I have attached the code snippet below.
export default class PocDetail extends React.Component {
constructor(props) {
super(props);
this.state={
isLoading:true,
editData:[],
};
}
componentDidMount(){
this.renderData();
}
renderData(){
var self = this;
const getOrgId =
window.location.href.substr(window.location.href.lastIndexOf('/') + 1);
const url = "some api";
get(url+"Organisation/"+getOrgId+"/pointOfContacts/").then(function (response) {
console.log(response.data);
self.setState({
editData:response.data,
isLoading:false
})
}).catch(function (error) {
console.log(error);
});
}
putData =(e)=>{
e.preventDefault();
}
//edit permission for input fields
inputChangedHandler = (event) => {
this.setState({ editData: { ...this.state.editData,[event.target.name]:event.target.value} });
// May be call for search result
}
//the view
render() {
const {isLoading,editData} = this.state;
if(isLoading){
return <Loader />;
}
return (
<div>
<Row style={{paddingTop:'20px',paddingBottom:'40px',marginLeft:'auto',marginRight:'auto'}}>
<Col lg="8" md="8" sm="8">
<Form id="bankForm" onSubmit={this.putData}>
<ToastContainer store={ToastStore}/>
{
editData.map(data=>{
return(<Row key={data.id}>
<Col lg="6" md="6" sm="6">
<FormGroup>
<Label className="createLabelStyle" for="title">Title</Label>
<Input className="createInputStyle" type="text" name="title" id="title" autoComplete="off" value={data.title} onChange={(event)=>this.inputChangedHandler(event)} required/>
</FormGroup>
<FormGroup>
<Label className="createLabelStyle" for="first_name">First name</Label>
<Input className="createInputStyle" type="text" name="first_name" id="first_name" value={data.first_name} onChange={(event)=>this.inputChangedHandler(event)} autoComplete="off" required/>
</FormGroup>
<FormGroup>
<Label className="createLabelStyle" for="contact_number">Contact Number</Label>
<Input className="createInputStyle" type="text" name="contact_number" id="contact_number" autoComplete="off" value={(data.contact_number==null)?"":data.contact_number} onChange={(event)=>this.inputChangedHandler(event)} required/>
</FormGroup>
</Col>
<Col lg="6" md="6" sm="6">
<FormGroup>
<Label className="createLabelStyle" for="email">Email ID</Label>
<Input className="createInputStyle" type="text" name="email" value={data.email} onChange={(event)=>this.inputChangedHandler(event)} id="email" autoComplete="off" required/>
</FormGroup>
<FormGroup>
<Label className="createLabelStyle" for="last_name">Last name</Label>
<Input className="createInputStyle" type="text" name="last_name" value={data.last_name} onChange={(event)=>this.inputChangedHandler(event)} id="last_name" autoComplete="off" required/>
</FormGroup>
</Col>
</Row>);
})
}
<Button className="createSubmitStyle">Add</Button>{' '}
<Button className="createSubmitStyle">Update</Button>
</Form>
</Col>
</Row>
</div>
);
}
}
In the renderData function variable editData is an Array that's why it is rendering your form properly but in the inputChangedHandler function you are updating editData to an Object hence the issue
Please try this snippet:
editData!=undefined &&editData.map(data=>{});
I found out the solution. Adding this code below solved the problem. I needed to add index with map to update the property value of object.
inputChangedHandler(i,event){
let data = [...this.state.editData];
data[i][event.target.name] = event.target.value;
console.log(data[i][event.target.name]);
this.setState({editData:data});
}

React Send form data to email

I am using create-react-app or my project. I created a form field where I store the data into the state. I would like to send the data as an email, and I'm lost on how to do so.
One of the problems is using create-react-app, I'm not sure where to find my router or server page in node.
Any help would be greatly appreciated.
import React, { Component } from 'react';
import { Button, Col, Grid, Row, Form, FormGroup, FormControl,
ControlLabel, Checkbox } from 'react-bootstrap';
export class Contact extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
message: ""
}
}
onChange = (e) => {
const state = this.state;
state[e.target.name] = e.target.value;
this.setState(state);
}
onSubmit = (e) => {
e.preventDefault();
const { name, email, message } = this.state;
}
render() {
const { name, email, message } = this.state;
return(
<div>
<Grid>
<Row id="contactForm">
<Col xs={2}>
</Col>
<Col xs={8}>
<Form horizontal onSubmit={this.onSubmit}>
<FormGroup >
<Col componentClass={ControlLabel} sm={2}>
Name
</Col>
<Col sm={10}>
<FormControl required value={name} name="name" type="name"
placeholder="Name" onChange={this.onChange} />
</Col>
</FormGroup>
<FormGroup controlId="formHorizontalPassword">
<Col componentClass={ControlLabel} sm={2}>
Email
</Col>
<Col sm={10}>
<FormControl required value={email} name="email" type="email"
placeholder="Email" onChange={this.onChange}/>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} bsSize="lg" sm={2}>
Message
</Col>
<Col sm={10}>
<FormControl required value={message} name="message" componentClass="textarea" style={{ height: 200 }}
type="message" placeholder="Insert message here" onChange={this.onChange}/>
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Checkbox>Flag as important</Checkbox>
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Button type="submit">
Send
</Button>
</Col>
</FormGroup>
</Form>
</Col>
<Col xs={2}>
</Col>
</Row>
</Grid>
</div>
)
}
}
Short answer is that You cannot send mail from the client. You will need to have a server to do so. If you have an api service that your React is consuming from, then it is very possible from there.

Resources