ReactJs form onSubmit handle not working - javascript

I have a ReactJs component. handleSubmit is not called when my form is submitted. I am using meteorJs as my backend and ReactJs as my frontend library. I don't know where is the problem. I tried commenting out everything except input tag but didn't work.
import React, {Component} from 'react';
export default class ConfessionPoster extends Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
//handle form submit
handleSubmit(event) {
event.preventDefault();
console.log("We are in handle");
console.log(this.state.value);
}
handleInputChange(event) {
event.preventDefault();
// const target = event.target;
// const confessionValue = target.value;
// const confessionName = target.name;
//
// this.setState({[confessionName]: confessionValue});
// console.log(this.state.confessionText);
this.setState({value: event.target.value});
console.log(this.state.value);
}
render() {
return (
<div id="confession-poster" className="modal">
<div className="modal-content">
<div className="row">
<div className="col s1">
<i className="material-icons prefix">account_circle</i>
</div>
<div className="col s11">
<h6>Kiran Kumar Chaudhary</h6>
</div>
</div>
<form onSubmit={this.handleSubmit}>
<div className="row confession-area">
<div className="input-field col s12">
<label htmlFor="confession-textarea">Your Confession</label>
<textarea id="confession-textarea" className="materialize-textarea" value={this.state.value} onChange={this.handleInputChange}/>
</div>
</div>
<div className="row">
<div className="col s12">
<i className="material-icons">photo_camera</i>
<i className="material-icons">link</i>
<i className="material-icons">location_on</i>
</div>
</div>
<div className="row">
<div className="input-field col s12">
<input type="checkbox" className="filled-in" id="hide-my-identity" defaultChecked/>
<label htmlFor="hide-my-identity">Hide my Identity</label>
</div>
</div>
<div className="row">
<input className="btn" type="submit" value="Post"/>
</div>
</form>
</div>
</div>
);
}
}

Related

How to add a background image avatar to React JS using primereact

I am trying to create a register page where a user can add a profile picture as well as a background picture to their profile. I have installed the PrimeReact themes and templates to my node modules. However, the avatar doesn't want to fit it to where it can make a background image avatar. Instead, it just fits it as a circle just like the profile picture avatar instead of a rectangle fit as a background image avatar.
import {useState, useEffect } from 'react'
import Avatar from 'react-avatar-edit'
import {Dialog} from 'primereact/dialog'
import {InputText} from 'primereact/inputtext'
const initialState = {
company: '',
email: '',
password: '',
isMember: true,
}
const Register = () => {
const [imagecrop, setimagecrop] = useState(false);
const [image, setImage] = useState("");
const [src, setsrc] = useState(false);
const [profile, setProfile] = useState([]);
const [pview, setpview] = useState(false);
const profileFinal = profile.map((item) => item.pview);
const onClose = () => {
setpview(null);
};
const onCrop = (view) => {
setpview(view);
};
const saveCropImage = () => {
setProfile([...profile, { pview }]);
setimagecrop(false);
}
const [values, setValues] = useState(initialState)
// global state and useNavigate
const handleChange = (e) => {
console.log(e.target)
}
const onSubmit = (e) => {
e.preventDefault()
console.log(e.target)
}
return (
<body class="page-template-default page page-id-13">
<header class="site-header">
<div class="container">
<h1 class="school-logo-text float-left"><strong>Direct</strong> Connection</h1>
<div class="site-header__util">
</div>
</div>
</header>
<div class="page-banner">
<div class="page-banner__bg-image" style={ { backgroundImage: "url('connection.jpg')" } }></div>
<div class="page-banner__content container container--narrow">
<h1 class="page-banner__title">Add Your Company</h1>
<div class="page-banner__intro">
<p></p>
</div>
</div>
</div>
<div class="container container--narrow page-section">
<h2 class="headline headline--tiny">Want to join and connect with companies? Sign up and get your company out there:</h2>
<label class="profile-pic">Profile Photo:</label>
<div class="profile-img">
<Dialog
visible={imagecrop}
header={() => (
<p htmlFor="" class="text 2xl font-semibold textColor">
</p>
)}
onHide={() => setimagecrop(false)}
></Dialog>
<div class="confirmation-content flex flex-column align-items-center">
<Avatar
width={500}
height={400}
onCrop={onCrop}
onClose={onClose}
src={src}
shadingColor={"#474649"}
backgroundColor={"#474649"}
></Avatar>
<div class="flex flex-column align-items-center mt-5 w-12">
<div class="flex justify-content-around w-12 mt-4">
</div>
</div>
<InputText
type="file"
accept='/image/*'
style={{ display: "none" }}
onChange={(event)=>{
const file = event.target.files[0];
if(file && file.type.substring(0,5)==="image"){
setImage(file);
}else{
setImage(null)
}
}}
/>
</div>
</div>
<script src="profile-pic.js"></script>
<label class="profile-back">Background Photo:</label>
<div>
<Dialog
visible={imagecrop}
header={() => (
<p htmlFor="" class="text 2xl font-semibold textColor">
</p>
)}
onHide={() => setimagecrop(false)}
></Dialog>
<Avatar
width={1000}
height={400}
onCrop={onCrop}
onClose={onClose}
src={src}
shadingColor={"#474649"}
backgroundColor={"#474649"}
></Avatar>
<InputText
type="file"
accept='/image/*'
style={{ display: "none" }}
onChange={(event)=>{
const file = event.target.files[0];
if(file && file.type.substring(0,5)==="image"){
setImage(file);
}else{
setImage(null)
}
}}
/>
<img class="background-image" src=""></img>
</div>
<div class="company-info-container page-section">
<label class="company-name">Company Name</label>
<div class="company-input">
<input text="headline headline--input" placeholder="Enter Company"></input>
</div>
<label class="company-email">Email</label>
<div class="email-input">
<input text="headline headline--input" placeholder="Enter Email"></input>
</div>
<label class="company-address">Company Address</label>
<div class="address-input">
<input text="headline headline--input" placeholder="Enter Address"></input>
</div>
<label class="company-city">City</label>
<div class="city-input">
<input text="headline headline--input" placeholder="Enter City"></input>
</div>
<label class="company-zip">Zip Code</label>
<div class="zip-input">
<input text="headline headline--input" placeholder="Enter Zip"></input>
</div>
<label class="company-password">Password</label>
<div class="password-input">
<input text="headline headline--input" placeholder="Enter Password"></input>
</div>
<label class="company-password">Retype Password</label>
<div class="reword-input">
<input text="headline headline--input" placeholder="Re Password"></input>
</div>
<label class="company-description">Tell us about your company and what you do!</label>
<div class="description-input">
<textarea rows="5" cols="80" id="TITLE" text="headline headline--input" placeholder="Description"></textarea>
</div>
</div>
<button type="button" class="btn btn--large btn--orange push-right">Add Your Company</button>
</div>
<footer class="site-footer">
<div class="site-footer__inner container container--narrow">
<div class="group">
<div class="site-footer__col-one">
<h1 class="school-logo-text school-logo-text--alt-color">
<strong>Direct</strong> Connection
</h1>
<p><a class="site-footer__link" href="index.html">706-263-0175</a></p>
</div>
</div>
</div>
</footer>
</body>
)
}
export default Register
I have tried looking at how primereact avatars can reshape the circle to rectangle to fit the image to a background image but I don't see many ways of how it can be reshaped.

ReCaptcha not showing up

I'm trying to display a simple ReCaptcha. However, it appears if I delete onloadCallback function and then re-add it. Then it disappears until I do this again.
I will attach the code that I use. Also, I add localhost as a domain and I install the package using npm. I will write hidden instead of the site key that I use. Also, I want to hide my submit form button if the ReCaptcha is not verified, for this, I use useState hooks.
import React, { useState, useEffect } from 'react';
import ReCAPTCHA from "react-google-recaptcha";
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import { collection, addDoc } from "firebase/firestore";
import {db} from "./firebase.js"
export default function Contact(){
const [captcha, setCaptcha] = useState(true);
const [formData, setFormData] = useState({
name: "",
phone: "",
subject: "",
message: ""
})
function handleOnChange(value){
setCaptcha(false);
console.log("recaptcha ", value);
}
function recaptchaLoaded() {
console.log('capcha successfully loaded');
}
function handleOnChange(value){
console.log("captcha value:" , value);
}
function handleChange(event){
const {name, phone, subject, message} = event.target
setFormData(prevFormData => ({
...prevFormData,
[event.target.name]: event.target.value
}))
}
function handleSubmit(event){
event.preventDefault();
try {
console.log(formData);
const docRef = addDoc(collection(db, "mesaje"), { formData });
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
}
return(
<section id="contact" class="contact">
<div class="container">
<div class="section-title" data-aos="zoom-out">
<h2>Contact</h2>
<p>Date de contact</p>
</div>
<div class="row mt-5">
<div class="col-lg-4" data-aos="fade-right">
<div class="info">
<div class="address">
<i class="bi bi-geo-alt"></i>
<h4>Locatie:</h4>
<p>Galati</p>
</div>
<div class="email">
<i class="bi bi-envelope"></i>
<h4>Email:</h4>
<p>carageamarian72#yahoo.com</p>
</div>
<div class="phone">
<i class="bi bi-phone"></i>
<h4>Telefon:</h4>
<p>0744635351</p>
</div>
</div>
</div>
<div class="col-lg-8 mt-5 mt-lg-0" data-aos="fade-left">
<form onSubmit={handleSubmit} class="php-email-form" >
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Nume" required onChange={handleChange}
value={formData.name}/>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="tel" class="form-control" name="phone" id="phone" placeholder="Telefon" required onChange={handleChange}
value={formData.phone} pattern="[0-9]{10}"/>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subiect" required onChange={handleChange}
value={formData.subject}/>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" rows="5" placeholder="Mesaj" required onChange={handleChange}
value={formData.message}></textarea>
</div>
<div class="my-3">
<div class="loading">Loading</div>
<div class="error-message">Eroare, mesajul nu a fost trimis!</div>
<div class="sent-message">Mesajul a fost trimis, te vom contacta imediat!</div>
</div>
<ReCAPTCHA
sitekey="hidden"
onChange={handleOnChange}
onloadCallback={recaptchaLoaded}
/>
<div class="text-center"><button type="submit" disabled={captcha}>Trimite mesaj</button></div>
</form>
</div>
</div>
</div>
</section>
);
}
i found the problem. I had 2 different types of recaptcha in my html folder. They were in conflict.
I also delete the onloadCallback props.

Why is html not printing on button click in reactjs?

I am trying to print "Hello" onto the screen when the add button is clicked. But it is not showing. Thank you in advance for any answers you may have!
import React, { Component } from 'react';
import './App.css';
import './Login.jsx';
import './Navbar.jsx';
class MainPage extends Component {
render() {
return (
<div>
<div className="main-container">
<h1 style={{textDecoration:'underline'}}>Tasks</h1>
<div className="input-group mb-3">
<input type="text" id="task" className="form-control" placeholder="New Task"/>
<div id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
</div>
</div>
</div>
</div>
);
}
addTask = () => {
return (
<div>
<h2>Hello</h2>
</div>
)
}
}
export default MainPage;
Returning an HTML in an onClickEvent make no sense, where are the result going to be displayed?
I would manage it with a state, something like this
class MainPage extends Component {
this.state = {
buttonPress:false
}
render() {
return (
<div>
<div className="main-container">
<h1 style={{textDecoration:'underline'}}>Tasks</h1>
<div className="input-group mb-3">
<input type="text" id="task" className="form-control" placeholder="New Task"/>
<div id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
{{this.state.buttonPress? <h2>Hello</h2> : <span/>}}
</div>
</div>
</div>
</div>
);
}
addTask = () => {
this.setState({buttonPress:true});
}
}
export default MainPage;
Where would the function return the "Hello" code?
import React, { Component } from 'react';
import './App.css';
import './Login.jsx';
import './Navbar.jsx';
class MainPage extends Component {
state = {
showMessage: false
}
addTask= () => {
this.setState({showMessage: true});
};
render() {
return (
<div>
<div className="main-container">
<h1 style={{textDecoration:'underline'}}>Tasks</h1>
<div className="input-group mb-3">
<input type="text" id="task" className="form-control" placeholder="New Task"/>
<div id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
{this.state.showMessage && <div>
<h2>Hello</h2>
</div>}
</div>
</div>
</div>
</div>
);
}
}
export default MainPage;
Try this code instead, I created a state which tracks the visibility of the div.
More information here:
How do I display text on button click in React.js
You should use state
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props)
this.state = {testVarible: null}
}
render() {
return (
<div>
<div className="main-container">
<h1 style={{textDecoration:'underline'}}>Tasks</h1>
<div className="input-group mb-3">
<input type="text" id="task" className="form-control" placeholder="New Task"/>
<div id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
</div>
</div>
</div>
{this.state.testVarible}
</div>
);
}
addTask = () => {
this.setState({testVarible: (
<div>
<h2>Hello</h2>
</div>
)});
}
}
export default App;

How to make ReactJS onClick function change the value of a textarea?

I am trying to make a ReactJS form in which there is a button which, once pressed, alters the value of an input tag. Every time I press the button, the text is changed, but the page reloads, and the textarea returns to being blank. I've searched up on this issue a little and found this thread : Reactjs every time refreshing page on setState.
However, the solution to this problem( shouldComponentUpdate() {return false;} ) ended up making it so that the text of the inputarea didn't change at all. Here is my code:
import React, { Component } from 'react';
export default class Header extends Component {
state = {
cep : "",
address : "",
}
searchCEP(){
this.setState({ address : "Adress" });
}
render(){
return (
<div>
<div id="host-form" className="row">
<div className="col s1"></div>
<form className="col s10">
<div className="row">
<div className="input-field col s6">
<input placeholder='"Terreno para churrasco"' id="title" type="text" className="validate"/>
<label htmlFor="title">Título</label>
</div>
<div className="input-field col s2">
<input id="cep" type="text" className="validate" defaultValue={this.state.cep}/>
<label htmlFor="cep">CEP</label>
</div>
<div id="buscar-cep" className="col s1">
<button onClick={() => this.searchCEP()} className="waves-effect blue waves-light btn">Buscar por CEP</button>
</div>
<div className="col s2"></div>
</div>
<div className="row">
<div className="input-field col s12">
<input placeholder='"Terreno de 500 metros quadrados com uma linda vista do Cristo Redentor...\"' id="description" type="text" className="validate"/>
<label htmlFor="description">Descrição</label>
</div>
</div>
<div className="row">
<div className="input-field col s12">
<input id="address" type="text" className="validate" defaultValue={this.state.address}/>
<label htmlFor="address">Endereço</label>
</div>
</div>
</form>
</div>
</div>
);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I hope this is enough to understand my problem. Thanks in advance for any help.
from reading what you said the best case reason as to why the page reloads, from past exprience is that when you call the function you do not prevent the default action of the button within the form so you could try
"""
searchCEP(e){
e.preventDefault();
this.setState({ address : "Adress" });
}
"""
<div id="buscar-cep" className="col s1">
<button onClick={(e) => this.searchCEP(e)} className="waves-effect blue waves-light btn">Buscar por CEP</button>
</div>
"""
Since
hope this helps
You can make following changes
<div id="buscar-cep" className="col s1">
<button onClick={(e) => this.searchCEP(e)} className="waves-effect blue waves-light btn">Buscar por CEP</button>
</div>
and in searchCEP function, do the following changes:
searchCEP(e){
e.preventDefault();
this.setState({ address : "Adress" });
}
This will stop the reloading
You should stop the default behavior of the form element :
<form onSubmit={(e) => e.preventDefault()}

state uses with authentication

i'm new in coding and i I still have a problem with if else condition, i have 2 authentication and one back end , one for react native and one for react ,
in Login i want to add is_store , i want to tell the system that if the username & password correct and is_sore = true , make him logged in and if the password right and the username right BUT is_store = false don't logged him in
i'm trying to pass is_store to Login component
i tried if condition but it give me wrong alert
Signup component
class RegistationForm extends Component {
state = {
username: "",
phone_number: "",
password: "",
email: "",
is_store: true <--- i want to pass it to Login
};
componentWillUnmount() {
this.props.errors.length && this.props.resetError();
}
changeHandler = e => {
this.setState({ [e.target.name]: e.target.value });
};
submitHandler = async e => {
e.preventDefault();
this.props.signup(this.state, this.props.history);
};
render() {
return (
<div className="container">
<div
style={{ marginTop: "125px" }}
className="card o-hidden border-0 shadow-lg col-12"
>
<div className="card-body p-0">
<div className="row">
<div className="col-lg-5 d-none d-lg-block bg-register-image col-12" />
<div className="col-lg-7 col-12">
<div className="p-5">
<div className="text-center col-12">
<h1 className="h4 text-gray-900 mb-4 col-12">
إنشاء حساب جديد
</h1>
</div>
<div className="text-center col-12">
{!!this.props.errors.length && (
<div className="text-left alert alert-danger">
{this.props.errors.map(error => (
<li key={error}>{error}</li>
))}
</div>
)}
</div>
<form onSubmit={this.submitHandler}>
<div className="form-group row">
<div className="col-sm-6 mb-3 mb-sm-0">
<Input
name="username"
value={this.state.username}
onChange={this.changeHandler}
className="form-control form-control-user"
placeholder=" السجل التجاري"
required
/>
</div>
<div className="col-sm-6 mb-3 mb-sm-0">
<Input
name="phone_number"
value={this.state.phone_number}
type="tel"
onChange={this.changeHandler}
className="form-control form-control-user"
placeholder="Mobile Ex: 966555555555"
required
pattern="[0-9]{12}"
/>
</div>
<br />
<br />
<div className="col-sm-6 mb-3 mb-sm-0">
<Input
name="password"
value={this.state.password}
onChange={this.changeHandler}
type="password"
className="form-control form-control-user"
placeholder="الرقم السري"
required
/>
</div>
<div className="col-sm-6 mb-3 mb-sm-0 ">
<Input
name="email"
value={this.state.email}
onChange={this.changeHandler}
type="email"
className="form-control form-control-user"
placeholder="الإيميل"
required
/>
</div>
<div className="col-12">
<button
style={{ padding: 9, marginTop: 20 }}
type="submit"
className="btn btn-success col-12 "
>
إنشئ حساب
</button>
</div>
</div>
</form>
<div className="text-center">
<Link to="/login" className="small">
املك حساب من قبل: تسجيل الدخول
</Link>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
Login component
class Login extends Component {
state = {
username: "",
password: "",
is_store: false <-- is here the right place?
};
componentWillUnmount() {
this.props.errors.length && this.props.resetError();
}
changeHandler = e => {
this.setState({ [e.target.name]: e.target.value });
};
submitHandler = async e => {
e.preventDefault();
## here is what i'm trying to do with is_store
if (this.state.is_store === true) {
this.props.login(this.state, this.props.history);
} else {
alert("Wrong");
}
};
render() {
return (
<div className="container">
<div className="row justify-content-center" style={{ marginTop: 125 }}>
<div className="col-xl-10 col-lg-12 col-md-9">
<div className="card o-hidden border-0 shadow-lg my-5">
<div className="card-body p-0">
<div className="row">
<div className="col-lg-6 d-none d-lg-block bg-login-image" />
<div className="col-lg-6">
<div className="p-5">
<div className="text-left">
<h1 className="h4 text-gray-900 mb-4">تسجيل الدخول</h1>
{!!this.props.errors.length && (
<div className="alert alert-danger" role="alert">
{this.props.errors.map(error => (
<li key={error}>{error}</li>
))}
</div>
)}
</div>
<form onSubmit={this.submitHandler}>
<div
className="form-group col-12"
style={{ padding: 0 }}
>
<Input
name="username"
className="form-control form-control-user"
onChange={this.changeHandler}
value={this.state.username}
placeholder="رقم السجل التجاري"
/>
</div>
<div
className="form-group col-12"
style={{ padding: 0 }}
>
<Input
type="password"
className="form-control form-control-user"
name="password"
value={this.state.passsword}
onChange={this.changeHandler}
placeholder="الرقم السري"
/>
</div>
<button
style={{ padding: 9 }}
type="submit"
className="btn btn-primary col-12"
>
دخول
</button>
<hr />
</form>
<hr />
<div className="text-center">
<NavLink to={`/signup`}>إنشاء حساب جديد</NavLink>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
this is authentication actions
export const login = (userData, history) => {
return async dispatch => {
try {
let response = await instance.post("user/login/", userData);
let user = response.data;
setAuthToken(user.token);
let decodedUser = jwt_decode(user.token);
dispatch(setCurrentUser(decodedUser));
history.push("/home");
} catch (error) {
console.log("error", error);
dispatch(setErrors(error.response.data));
}
};
};
thank you
In general, You can pass a state to a child component only. You can not pass a state from a child to its parent component.
In order to pass state to a parent component, you need to store that value. You can do it with Redux. Which stores the values and you can get that value in any component.

Categories