Netify-gatsby form submission not working with custom Success Component - reactjs

I am using Netify-form with gatsby JS. I am trying to show a success alert Component when a user submits the form. This is working fine, but I am not able to get form data under my Netify account.
handleSubmit = (e) => {
this.setState({showSuccessMsg: true});
e.preventDefault();
};
<form name="subscribe"
method="POST"
onSubmit={this.handleSubmit} // custom handler
action=""
data-netlify="true"
data-netlify-honeypot="bot-field"
className="form-inline d-flex">
<input type="hidden" name="form-name" value="subscribe"/>
<input type="hidden" name="bot-field"/>
.....
.....
<button type="submit" className="btn btn-primary mx-auto">
Subscribe
</button>
</form>
<div>
{this.state.showSuccessMsg ? <SuccessAlert/> : ''}
</div>
PS: commenting this // onSubmit={this.handleSubmit}, I am able to get data but I am loosing showing success alert.

Netlify forms setup - Success messages
By default, when visitors complete a form, they will see a generically styled success message with a link back to the form page. You can replace the default success message with a custom page you create by adding an action attribute to the tag, entering the path of your custom page (like "/pages/success") as the value. The path must be relative to the site root, starting with a /.
Or you could check out this guide from Netlify - How to Integrate Netlify’s Form Handling in a React App which has a gatsby specific example for submitting with js.
import React, {useState} from 'react'
function encode(data) {
return Object.keys(data)
.map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
.join('&')
}
export default function Contact() {
const [state, setState] = useState({})
const handleChange = (e) => {
setState({ ...state, [e.target.name]: e.target.value })
}
const handleSubmit = (e) => {
e.preventDefault()
const form = e.target
fetch('/', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: encode({
'form-name': form.getAttribute('name'),
...state,
}),
})
.then(() => alert('success')))
.catch((error) => alert(error))
}
return (
<>
<h1>Contact</h1>
<form
name="contact"
method="post"
action="/thanks/"
data-netlify="true"
data-netlify-honeypot="bot-field"
onSubmit={handleSubmit}
>
{/* The `form-name` hidden field is required to support form submissions without JavaScript */}
<input type="hidden" name="form-name" value="contact" />
<div hidden>
<label>
Don’t fill this out: <input name="bot-field" onChange={handleChange} />
</label>
</div>
<label>
Your name:
<input type="text" name="name" onChange={handleChange} />
</label>
<label>
Your email:
<input type="email" name="email" onChange={handleChange} />
</label>
<label>
Message:
<textarea name="message" onChange={handleChange} />
</label>
<button type="submit">Send</button>
</form>
</>
)
}

Related

React How do I extract data from a form when triggering onSubmit event?

I am messing around with Riot's API that allows getting information of a player by the player's name. I am trying to get an API key (I only got a 24 hour key) and the target player's name from users' input.
export function PlayerSearch() {
function handlesubmit(e) {
console.log(e.target);
e.preventDefault();
}
return (
<div className='player'>
<div className='inputfield'>
<form onSubmit={handlesubmit} method='GET' autoComplete="off">
<div>
<label htmlFor="key">Your API key:</label>
<input
placeholder='Your API key'
onFocus={(e)=>{e.target.placeholder=''}}
type="text"
id="key"
name="key" />
</div>
<div>
<label htmlFor="name">Player name:</label>
<input
placeholder='Player name'
onFocus={(e)=>{e.target.placeholder=''}}
type="text"
id="name"
name="name" />
</div>
<div>
<input type='submit' />
</div>
</form>
</div>
</div>
);
}
And I got this in the console:
So how exactly do I extract the two inputs from the form?
In addition, is it possible that I can call another component and pass data as props to handle the submitted data so that the code is cleaner?
You should have a state to store your inputs:
const [formData, setFormData] = useState({ key: "", name: "" });
Then you need a function that gets called onChange of your input fields to update your state:
const onChange = (event) => {
setFormData({ ...formData, [event.target.name]: event.target.value });
};
And you need to pass that function to your input onChange property:
<input
placeholder="Your API key"
onFocus={(e) => {
e.target.placeholder = "";
}}
type="text"
name="key"
value={formData.key}
onChange={onChange}
/>
Then you can access the state in your handleSubmit:
function handlesubmit(e) {
console.log(formData);
e.preventDefault();
}

Sending email in react js

I am new to react. I need to know how to send a mail in react. There is no forms.
When I search in google, everything comes with a form fill up.
I just need a simple function, that triggers to send mail.
Can anyone help with that?
** Used EmailJs https://www.emailjs.com/ here to get the message from the user.**
import emailjs from '#emailjs/browser';
import React, { useRef } from 'react';
function ContactForm() {
const form = useRef();
//console.log('Hello');
const sendEmail = (e) => {
e.preventDefault();
emailjs.sendForm('****', 'template_****', form.current, '****')
.then((result) => {
console.log(result.text);
alert('Message sending successfully!');
form = "";
}, (error) => {
console.log(error.text);
});
};
<div>
<h4>inquiry</h4>
<h3>Stay connected with us</h3>
<form ref={form} onSubmit={sendEmail}>
<div>
<input type="text" id="name" required placeholder='Your full name' name="user_name" />
</div>
<div>
<input type="email" id="email" required placeholder='Your email address' name="user_email" /></div>
<div>
<textarea id="message" required placeholder='Your message' name="message" />
</div>
<button type="submit" value="Send">Send</button>
</form>
</div>
Hope it would be helpful if you only want to get info from user.

How to empty/clear a react form fields after passing form data to fire base data base?

I am validating and passing react form data to fire base data base through react hook form. It's validate and pass but form fields remain filled. I want after passing data to data base form fields will be empty/clear. So what should I do??There is which I try
import React from "react";
import "./App.css";
import { useForm } from "react-hook-form";
import classNames from "classnames";
function App() {
const { register, handleSubmit,formState: { errors } } = useForm();
const onSubmit = async (data) => {
console.log(data);
// send data to firebase API
const responseRaw = await fetch(
"https://test1-5022f-default-rtdb.firebaseio.com/reactformData.json",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
const response = responseRaw.json();
};
There are many fields in my form but here I show some fileds
<form name="Registration_form" id="Form" action="" method="POST" onSubmit={handleSubmit(onSubmit)}>
<div className="form-group my-3">
<label htmlFor="name">Name:</label>
<input
type="text"
name="Name"
id="Name"
className={classNames("form-control",{"is-invalid":errors.Name,})}
autoComplete="off"
{...register('Name',
{ required: true,
maxLength: 15,
pattern: /^[A-Za-z]+$/
})
}
/>
<span id="name" className="text-danger fw-bold">{errors.Name?.type === "required" && "This field is required"}</span>
<span id="name" className="text-danger fw-bold">{errors.Name?.type ==="maxLength" && "Length Should be less then 15"}</span>
<span id="name" className="text-danger fw-bold">{errors.Name?.type === "pattern" && "Digits are not allow"}</span>
</div>
<div className="form-group my-3">
<label htmlFor="email">Email: </label>
<input
type="text"
name="email"
id="email"
className={classNames("form-control",{"is-invalid":errors.email,})}
placeholder="email#example.com"
autoComplete="off"
{...register('email',
{
required: true,
pattern:/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/,
})
}
/>
<span id="mail" className="text-danger fw-bold">{errors.email?.type === "required" && "Email is required"}</span>
<span id="mail" className="text-danger fw-bold">{errors.email?.type === "pattern" &&"Invalid format"}</span>
</div>
<input type="submit" id="submit" value="submit" className="btn btn-success my-3" />
</form>
That is code which i try for validation and passing data to data base through react hook form. But no I stuck here how to empty/clear all form fields after passing data to data base?
There's a reset function inside useForm that you can use
function App() {
const {
register,
handleSubmit,
formState: { errors },
reset,
} = useForm();
const onSubmit = async (data) => {
console.log(data);
// send data to firebase API
// call reset here
reset();
};
}

React form POST to Express server not working - REST

I am trying to POST a HTML form to an Express server.
When I use a REST client, the POST request works fine and data is correctly sent and registered in DB. So server-side looks good. But my React code won't POST anything. There is no error in the console and input values are correctly targetted. I've tried native fetch method and also Axios, but both are not working. I hope someone will help me on that as I'm not very familiar with REST api's yet.
Here is my Form component :
import React, { useState } from "react";
import Header from "./Header";
import Footer from "./Footer";
const Form = () => {
{/* POST REQUEST */}
const handleFormSubmit = (event) => {
const name = event.target.elements.name.value;
const description = event.target.elements.description.value;
const email = event.target.elements.email.value;
const number = event.target.elements.number.value;
const website = event.target.elements.website.value;
const social_media1 = event.target.elements.social_media1.value;
fetch("http://192.168.1.101:7777/form", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: name,
description: description,
email: email,
number: number,
website: website,
social_media1: social_media1,
}),
})
.then((response) => {
console.log(response);
return response.json();
})
.catch((error) => console.log(error));
};
return (
<>
{/* SOME PAGE STUFF */}
<Header />
<div className="formTitle">
<h3>Create your artist page</h3>
<p>Some fields are required</p>
</div>
{/* HTML FORM */}
<form onSubmit={handleFormSubmit} className="form">
<div>
<legend>About you</legend>
{/* NAME */}
<label htmlFor="name">
Artist name <span className="required">required</span>
</label>
<input
type="text"
id="name"
name="name"
required
placeholder="Oasis"
/>
</div>
<div>
{/* DESCRIPTION */}
<label htmlFor="description">
Description <span className="required">required</span>
</label>
<textarea
rows="5"
type="text"
id="description"
name="description"
required
placeholder="Insert a short description here"
></textarea>
</div>
<div>
<legend>Contact</legend>
{/* EMAIL */}
<label htmlFor="email">
Email address <span className="required">required</span>
</label>
<input
type="email"
id="email"
name="email"
required
placeholder="contact#oasis.uk"
/>
{/* NUMBER */}
<label htmlFor="number">Phone number </label>
<input
type="text"
id="number"
name="number"
required
placeholder="+34 6 12 34 56 78"
/>
{/* WEBSITE */}
<label htmlFor="website">Website </label>
<input
type="text"
id="website"
name="website"
required
placeholder="https://oasis.com"
/>
</div>
<div>
<legend>Social media</legend>
{/* SOCIAL LINK 1 */}
<label htmlFor="social_media1">
Social media link 1 <span className="required">required</span>
</label>
<input
type="text"
id="social_media1"
name="social_media1"
required
placeholder="https://instagram.com/oasis"
/>
</div>
<button className="submit" type="submit">
Submit
</button>
</form>
<div className="temp"></div>
<Footer />
</>
);
};
export default Form;
You can try this method:
const form_Data = new FormData(event.target);
const finalData = {};
for (let [key, value] of form_Data.entries()) {
finalData[key] = value;
}
console.log(finaldata);
fetch("http://192.168.1.101:7777/form", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: finaldata
})
.then((response) => {
console.log(response);
return response.json({response);
})
.catch((error) => console.log(error));
};
First, you should convert all form data into new FormData and you can pass this object to you fetch's POST method
I think it should be work.

Laravel React MySQL Routing Issue

I am trying to make it so that I can register a user but I am getting a 404 error, assuming that means that react is unable to find the route established by the api.php file, is there anything else that I am missing? I have already set it in the package.json file that the proxy is set to "localhost:8000" (the port I chose to use for laravel's backend stuff). I am confused on why it's not hitting this route upon submitting. I feel like I'm close but I am new to using php as the backend so any insight would be helpful.
I am also creating something where the user is able to play music on the app, so there is a route for that labeled "shop", and that does not work for the sole reason that I have not set that route up (also gives a 404 error).
Below are my api routes that I am trying to get react to detect
<?php
Route::post('register','UserController#register');
Route::post('login','UserController#login');
Route::post('profile','UserController#getAuthenticatedUser');
Route::middleware('auth:api')->get('/user', function(Request $request){
return $request->user();
});
?>
And this is the React portion of my registration file.
import React, { Component } from 'react';
import { register } from './UserFunctions';
class Register extends Component {
constructor() {
super()
this.state = {
first_name: '',
last_name: '',
email: '',
password: '',
errors: {},
}
this.onChange = this.onChange.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value })
}
onSubmit(e) {
e.preventDefault()
const newUser = {
name: this.state.first_name + ' ' + this.state.last_name,
email: this.state.email,
password: this.state.password
}
register(newUser).then(res => {
if (res) {
this.props.history.push('/login')
}
})
}
render() {
return (
<div className="container">
<div className="row">
<div className="col-md-6 mt-5 mx auto">
<form noValidate onSubmit={this.onSubmit}>
<h1 className="h3 mb-3 font-wieght-normal">
Register
</h1>
<div className="form-group">
<label htmlFor="first_name">First Name</label>
<input type="text" className="form-control" name="first_name" placeholder="Enter First Name" value={this.state.first_name} onChange={this.onChange} />
<label htmlFor="last_name">Last Name</label>
<input type="text" className="form-control" name="last_name" placeholder="Enter Last Name" value={this.state.last_name} onChange={this.onChange} />
<label htmlFor="email">Email Address</label><br />
<input type="email" className="form-control" name="email" placeholder="Enter Email" value={this.state.email} onChange={this.onChange} />
<br />
<label htmlFor="password">Desired Password</label><br />
<input type="password" className="form-control" name="password" placeholder="Enter Password" value={this.state.password} onChange={this.onChange} />
</div>
<button type="submit" className="btn btn-lg btn-primary btn-block">Register</button>
</form>
</div>
</div>
</div>
)
}
}
export default Register
I have those post routes defined, but when I press submit within my register form, I get a 404 error saying that it can't find this route.
Can you show me your
import { register } from './UserFunctions';
file so that I can see the url path defined.
Assuming this route is inside your routes/api.php
Route::group(['middleware' => 'api', 'prefix' => 'v1'], function(){
Route::post('register', 'RegisterController#index');
});
and in JS file
import axios from 'axios'
export const register = newUser => {
return axios
.post('api/v1/register', newUser,
{
headers: { 'Content-Type': 'application/json' }
})
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
}

Resources